0

这是我的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......(发现很多其他帖子,但似乎没有一个解决方案对我有用)

请帮忙 ...

提前致谢。

4

1 回答 1

-1

我昨天有同样的问题。从 DataContext 类中删除 getter 和 setter 很有帮助。顺便说一句,我会通过添加更改 CustomerId 列属性AutoSync=Autosync.OnInsert

于 2014-04-06T12:38:23.267 回答