2016-03-21 150 views
0

我的問題是,您是否可以使用實體框架輕鬆生成第三層數據。我一直都在使用他們,我知道兩層外鍵工作,但是三個?實體框架,在外鍵上播種

我的數據結構如下。

頂級表

表一 - 公司(一對多地區) - 「清單」地區

表二 - 地區(一對多產品) - 「list」 Items

表3-項目(Ma紐約到一) - 項目ID 目前爲兩個級別(公司和領域)之間的語法正常工作:

var NewCompany = new Company() { 

     Areas = new List<Area>(){ 

     Areaid = 0 

    } 
} 
      _context.Company.Add(NewCompany); 
      _context.Areas.AddRange(NewCompany.Areas); 

的問題是如何實現以下,加入第三個表作爲一個列表區域。

var NewCompany = new Company() { 

     Areas = new List<Area>(){ 

     Items = new List<Items>(){ 
     itemId= 1 
     } 

    } 
} 
      _context.Company.Add(NewCompany); 
      _context.Areas.AddRange(NewCompany.Areas); 
      _context.Areas.AddRange(NewCompany.Areas.Items); 
+0

請正確使用標籤。這個問題與sq-server無關。謝謝。 – FLICKER

回答

0

理想的情況下,如果你指定的約束以及數據庫和配置的模型正確,那麼你就不需要對相關實體(區&項目)添加到實體初步認識集合。

var NewCompany = new Company() { 
     Areas = new List<Area>(){ 
     Areaid = 0 
     Items = new List<Item>(){ 
      new Item(1), 
      new Item(2) 
      ... 
      ... 
     } 
    } 
} 

//just add newCompany instance to the entity collection rest should be automatically taken care. 
_context.Company.Add(NewCompany); 
//no need to write below statement. 
//_context.Areas.AddRange(NewCompany.Areas); 
+0

你是對的。我正在編寫一個教程,建議您必須始終按照上面的方式進行操作。刪除額外的增加和外鍵正確工作就好! – Caz1224