2014-04-04 49 views
0

這裏是我的DataContext類:InsertOnSubmit方法引發的NullReferenceException ... LINQ to SQL的C#實體/ 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

昨天我有同樣的問題。從DataContext類中刪除getter和setter幫助。順便說一句,我會通過添加AutoSync=Autosync.OnInsert

+0

更改CustomerId列屬性這不會提供問題的答案。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 – TheCodeArtist

+0

你在說什麼@TheCode藝術家?這顯然試圖回答這個問題。 – Ben

+0

@Ben Pardon我的快速觸發器。我只是在評論中標記了帖子,因此評論被添加了。我同意這感覺比我的意思強一點。這就是說,答案是非常抽象的,沒有一個例子/細節,確切地說需要做什麼。也不是我的專業領域,因此無法自己添加細節。 – TheCodeArtist