2016-11-03 26 views
0

這是我插入客戶和嵌套子對象的方式。客戶有孩子叫地址和地址有孩子叫聯繫人詳細信息。實體框架:如何在向數據庫添加或更新數據期間包含嵌套子對象

using (var db = new TestDBContext()) 
    { 
     var customer = new Customer 
     { 
      FirstName = "Test Customer1", 
      LastName = "Test Customer1", 
      Addresses = new List<Addresses> 
      { 
       new Addresses 
       { 
        Address1 = "test add1", 
        Address2 = "test add2", 
        IsDefault=true, 
        Contacts = new List<Contacts> 
        { 
         new Contacts { Phone = "1111111", Fax = "1-1111111",IsDefault=true, SerialNo=1 }, 
         new Contacts { Phone = "2222222", Fax = "1-2222222",IsDefault=false, SerialNo=2 } 
        } 
       }, 
       new Addresses 
       { 
        Address1 = "test add3", 
        Address2 = "test add3", 
        IsDefault=false, 
        Contacts = new List<Contacts> 
        { 
         new Contacts { Phone = "33333333", Fax = "1-33333333",IsDefault=false, SerialNo=1 }, 
         new Contacts { Phone = "33333333", Fax = "1-33333333",IsDefault=true, SerialNo=2 } 
        } 
       } 

      } 
     }; 

     db.Customer.Add(customer); 
     db.SaveChanges(); 

     int id = customer.CustomerID; 
    } 

現在假設我想更新客戶及其相關地址和聯繫人詳細信息。

我瀏覽器幾個類似的線程在這裏。我看到有人刪除子數據並插入新數據而不是更新。這裏是一個鏈接https://stackoverflow.com/a/27177623/728750

它們包括孩子這樣

var existingParent = _dbContext.Parents 
     .Where(p => p.Id == model.Id) 
     .Include(p => p.Children) 
     .SingleOrDefault(); 

但對我來說,我有多個孩子說喜歡地址和聯繫方式,然後我怎麼能包括客戶的首地址,然後我想包括聯繫方式地址的孩子。

請告訴我該怎麼做。

回答

0

您是否在尋找這個

using System.Data.Entity; // NB! 

var company = dbContext.Parents 
        .Include(co => co.Addresses.Select(ad=> ad.Contacts)) 
        .FirstOrDefault(p => p.Id == model.Id); 

簡要樣品

var company = context.Companies 
       .Include(co => co.Employees.Select(emp => emp.Employee_Car)) 
       .Include(co => co.Employees.Select(emp => emp.Employee_Country)) 
       .FirstOrDefault(co => co.companyID == companyID); 

.Include Msdn細節總結

要包括收集,收集和參考兩級 下來: query.Include(e => e.Level1Collection.Select(l1 => l1.Level2Collection.Select(l2 => l2.Level3Reference)))

+0

是的,它的工作。假設我們有多個嵌套實體,那我該怎麼做。可以發佈示例代碼,其中嵌套實體是說5。 – Mou

+0

很高興,它幫助你 – Eldho

+0

我想嵌套像公司>國家>州>城市如何實現這一點 – Mou

相關問題