2012-09-26 55 views
0

許多關係,我有以下:實體框架的一個 - 保存

if (chemexist == false) // conditionally creating WtrChem record 
    { 
     WtrChem wc = new WtrChem(); 
     wc.Contact = "John Smith"; 
     .. 
     wc.Phone = ("800-888-9988"); 
     Db.WtrChem.Add(wc); 
     Db.SaveChanges(); 
    } 


    WtrChemDetail psw = new WtrChemDetail(); // creating details record for WtrChem 
    psw.Comments = comment; 
    .. 
    .. 
    Db.WtrChemDetail.Add(psw); 
    Db.SaveChanges(); 

的代碼將首先創建主記錄,然後創建一個詳細記錄。我有什麼作品。我想知道是否有一種更有效的方式來做最佳實踐方面的上述工作。

回答

0

您可能想對此模型進行建模,其中的細節是主模型上的屬性。

像這樣的東西可能:

// Get the item. Include makes sure that you get the referenced detail as well. 
WtrChem wc = Db.WtrChem.Include(x => x.Detail).SingleOrDefault(); 

if (wc == null) // creating WtrChem record 
{ 
    // If it wasn't found, create and add 
    wc = new WtrChem(); 
    Db.WtrChem.Add(wc); 
} 

wc.Contact = "John Smith"; 
.. 
wc.Phone = ("800-888-9988"); 

// Deal with the 
WtrChemDetail psw = new WtrChemDetail(); // creating details record for WtrChem 
psw.Comments = comment;  
wc.Detail = psw; 

Db.SaveChanges(); 

如果使用這種方法,主機和詳細的參考值將自動排序。

您需要,以使.Include(..)拉姆達工作添加using語句:

using System.Data.Entity; 
+0

謝謝你的生存。不管chemexist是否屬實,我都想創建一個細節記錄。另外是細節關鍵字?當我輸入時,它不會顯示在intellisense中。 –

+0

您需要在類「WtrChem」中創建類型爲「WtrChemDetail」的屬性,以使我的建議工作。我將編輯這個例子來處理另一件事。 –