简体   繁体   English

Linq to SQL删除/添加子对象

[英]Linq to SQL Delete/Add Child objects

I have a customer table which has a child table called customer addresses. 我有一个客户表,其中有一个称为客户地址的子表。

Customer: 顾客:

CustomerID
Name
IsActive

CustomerAddresses: 客户地址:

CustomerAddressID
CustomerID
Street
City
State
ZipCode

I would like to update the customer table with a list of customer addresses and have it automatically remove/add the entries if they already exist. 我想用客户地址列表更新客户表,并让它自动删除/添加条目(如果已经存在)。

Does linq to SQL do this automatically or does it have to be done manually. linq to SQL是自动执行此操作还是必须手动执行。

You have to synchronize manually. 您必须手动进行同步。

I'm not sure this is the best method. 我不确定这是最好的方法。 But it's an option: 但这是一个选择:

var preExistentIds = (from x in context.CustomerAddresses select x.CustomerAddressID).ToList();

foreach (var deleted in preExistentIds.Where(x => !newCustomerAddr.Exists(y => y.CustomerAddressID == x)))
{
    var entity = new CustomerAddresses { CustomerAddressID = deleted.CustomerAddressID };
    context.CustomerAddresses.Attach(entity);
    context.Entry(entity).State = EntityState.Deleted;
}

foreach(var item in newCustomerAddr){
    var entity = new CustomerAddresses { CustomerAddressID = item.CustomerAddressID };
    context.CustomerAddresses.Attach(entity);
    entity.Fields = item.Field;
    [..]
    context.Entry(entity).State = item.CustomerAddressID == 0? EntityState.Added : EntityState.Modified;
}

db.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM