InsertOnSubmit方法抛出NullReferenceException ... Linq到sql C#entity / DataContext类

时间:2014-04-04 14:41:31

标签: linq-to-sql entity insertonsubmit

这是我的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);
    }

我现在用Google搜索了好几个小时,我无法弄清楚为什么它会抛出NullReferenceException ...(发现很多其他帖子但是没有解决方案似乎适用于我)

请帮忙......

提前致谢。

1 个答案:

答案 0 :(得分:-1)

昨天我遇到了同样的问题。从DataContext类中删除getter和setter有所帮助。顺便说一句,我通过添加AutoSync=Autosync.OnInsert

来更改CustomerId列属性