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
...(發現了很多其他職位,但解決方案的非似乎爲我工作)
請幫助...提前
謝謝。
更改CustomerId列屬性這不會提供問題的答案。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 – TheCodeArtist
你在說什麼@TheCode藝術家?這顯然試圖回答這個問題。 – Ben
@Ben Pardon我的快速觸發器。我只是在評論中標記了帖子,因此評論被添加了。我同意這感覺比我的意思強一點。這就是說,答案是非常抽象的,沒有一個例子/細節,確切地說需要做什麼。也不是我的專業領域,因此無法自己添加細節。 – TheCodeArtist