2011-05-17 105 views
0

讓我們把這個簡單的... 假設我有2個實體:實體框架保留幽靈實體?

 
Application 
    Id: int (primary key, autoincrement) 
    Name: string(60) 
    Client: User 
    SupportEngineer: User 

User 
    Id: int (primary key, autoincrement) 
    Name: string(60) 
    EmailAddress: string(60) 

還假設我有beign參與了一個名爲沒有上下文創建一個接收創建的應用程序的一個實例(在另一層)方法:

 
    var application = new Application 
     { 
      Name = "Visual Studio 2010", 
      Client = new User { Id = 12 }, 
      SupportEngineer = new User { Id = 14 } 
     }; 

請注意,具有Id == 12和== 14的用戶存在於數據庫中!

 
    public void Create(Application application) { 
    application.Client = Context.Users.FirstOrDefault(e => e.Id == application.Client.Id); 
    application.SupportEngineer = Context.Users.FirstOrDefault(e => e.Id == application.SupportEngineer.Id); 
    Context.Applications.AddObject(application); 
    Context.SaveChanges(); 
    } 

當我調用的SaveChanges之前檢查在上下文中的對象,我得到調用爲「補充」 Create方法之前創建的用戶對象。

爲什麼,如果我重寫屬性客戶端和SupportEngineer的值與數據庫中的對象是怎麼回事? 爲什麼手動創建的對象(new User { Id = 12 }, new User { Id = 14 })仍然處於「添加」狀態的環境中?

+0

這裏真正的問題是什麼?創建調用後,Application的狀態是否無效? – 2011-05-17 21:22:22

+0

真正的問題是,EF將嘗試創建/插入兩個新用戶這是不希望的behaivor – 2011-05-17 21:56:59

+0

你看你調用'AddObject'之前做些什麼狀態?上下文之外創建 – 2011-05-17 22:02:24

回答

0

只是這樣做:

var application = new Application 
    { 
     Name = "Visual Studio 2010", 
     ClientId = 12, 
     SupportEngineerId = 14 
    }; 

並具備創建方法只需要創建一個對象:

public void Create(Application application) { 
    Context.Applications.AddObject(application); 
    Context.SaveChanges(); 
} 

不是一個直接的答案,但一些常規提醒:

你可能想另一件事注意,它看起來好像你正在重用你的DbContext。這通常是一個壞主意,特別是在添加/刪除對象時。例如,在刪除之後,刪除的對象仍然被上下文所知。相反,我會推薦一個模式,如:

using(var ctx = new MyContext()) 
{ 
    ctx.Applications.Add(application); 
    ctx.SaveChanges(); 
} 
+0

各地保持我沒有這些屬性(客戶端Id,SupportEngineerId),因爲不包括外鍵模型的一部分生成我的模型。儘管 – 2011-05-17 21:55:52

+0

這種行爲與開箱生成的代碼發生了,我使用的插件「ADO.NET實體POCO生成器」生成波蘇斯和設置ctx.ContextOptions.ProxyCreationEnabled = FALSE解決我有 – 2011-05-17 23:49:08

+0

ctx.ContextOptions.ProxyCreationEnabled問題= false創建了我沒有的其他問題。 – 2011-05-18 15:24:40