Here's my DataContext
class:
public class Dealer : DataContext
{
public Table<Vehicle> Vehicles;
public Table<Customer> Customers => GetTable<Customer>();
public Table<Account> Accounts;
public Table<Transaction> Transactions;
public Dealer(string connection) : base(connection) { }
}
Here's the Customer
Class:
[Table(Name="Customers")]
public class Customer
{
[Column(IsPrimaryKey = true, DbType = "int NOT NULL IDENTITY", IsDbGenerated = true, CanBeNull = false)]
public int CustomerID { get; set; }
[Column(CanBeNull = false)]
public string FirstName { get; set; }
[Column(CanBeNull = false)]
public string LastName { get; set; }
[Column(CanBeNull = false)]
public string SSN { get; set; }
public override string ToString()
{
return string.Concat(this.FirstName, " ", this.LastName, " ", this.SSN);
}
private EntitySet<Vehicle> vehicles = null;
[Association(Storage = "vehicles", OtherKey = "CustomerID", ThisKey = "CustomerID")]
public EntitySet<Vehicle> Vehicles { get; set; }
//implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Here's the code that throws the NullReferenceException
:
private void Button_Click(object sender, RoutedEventArgs e)
{
Customer c = new Customer() { FirstName="John", LastName="Smith", SSN = "123456" };
Dealer d = new Dealer(App.connectionString);
d.Customers.InsertOnSubmit(c); //d.Customers is null and throws null reference exception.!!!
try
{
d.SubmitChanges();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
I have googled for many hours now and I can't figure out why it's throwing NullReferenceException
... (found a lot of other posts but non of the solutions seem to work for me )
Please help ...
Thanks in advance.
I had the same problem yesterday. Removing getters and setters from DataContext class helped. By the way I'd change CustomerId column property by adding
AutoSync=Autosync.OnInsert