这是我的DataContext
课:
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) { }
}
这是Customer
课程:
[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));
}
}
这是抛出的代码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);
}
我已经用谷歌搜索了好几个小时,但我无法弄清楚它为什么会抛出NullReferenceException
......(发现很多其他帖子,但似乎没有一个解决方案对我有用)
请帮忙 ...
提前致谢。