【发布时间】: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