【问题标题】:Entity Framework: How to include nested child during add or update data to db实体框架:如何在向数据库添加或更新数据期间包含嵌套子项
【发布时间】:2017-03-16 23:40:31
【问题描述】:

以下方式我插入客户和嵌套的孩子。客户有孩子叫地址,地址有孩子叫联系人详细信息。

    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();

但在我的情况下,我有多个孩子说地址和联系方式,那么我怎么能包括客户的第一个地址,然后我想包括地址的孩子的联系方式。

请告诉我怎么做。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    你在找这个吗

    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)))

    【讨论】:

    • 是的,它奏效了。假设如果我们有许多多个嵌套实体,那么我该怎么做。可以发布嵌套实体为 5 的示例代码。
    • 很高兴,它帮助了你
    • 我想嵌套像公司 > 国家 > 州 > 城市如何实现这个
    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多