我使用VS2010,EF4功能CTP(最新版本),以及POCO對象,如下面的例子:EF4 POCO一對多導航屬性爲null
class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual IList<Account> Accounts { get; set; }
...
}
class Account
{
public string Number { get; set; }
public int ID { get; set; }
...
}
爲簡便起見,假設下面的context
是EF4的上下文對象。我有實體類型和數據庫之間的DBML映射,我使用它像這樣沒有問題:
Person doug = context.Persons.CreateObject();
doug.Name = "Doug";
context.Add(doug);
context.Save();
doug.Accounts.Add(new Account() { Name = "foo" });
context.Save(); // two calls needed, yuck
在這一點上,該數據庫有一個名爲「道」一個人的記錄,並且帳戶記錄「富」。我可以查詢並將這些記錄恢復正常。但是,如果我嘗試在之前添加帳戶,我保存該人員,則帳戶列表爲空(代理尚未在該特性上創建實例)。看下面的例子:
Person doug = context.Persons.CreateObject();
doug.Name = "Doug";
doug.Accounts.Add(new Account() { Name = "foo" }); // throws null reference exception
context.Add(doug);
context.Save();
有沒有其他人遇到過這個?更好的是,有沒有人找到一個好的解決方案?
我已經編輯我的問題澄清,我不是問的構造方案,但'context.Persons.CreateObject();'行爲。我的困惑是,如果框架在保存對象後要「擁有」那些導航屬性,爲什麼它在創建實體實例時不這樣做?我將集合初始化放在我的實體的構造函數中沒有問題,但是如果框架期望這些集合是'null',那麼看起來我將該對象置於壞狀態。 – 2010-01-05 19:33:33