Asp.net core ef core可以通过额外的文件进行多次更新
我的模式类:Asp.net core ef core可以通过额外的文件进行多次更新,asp.net-core,entity-framework-core,Asp.net Core,Entity Framework Core,我的模式类: public class AccountCustomer { public bool IsMain { get; set; } public int AccountId { get; set; } public Account Account { get; set; } public int CustomerId { get; set; } public Customer Customer {
public class AccountCustomer
{
public bool IsMain { get; set; }
public int AccountId { get; set; }
public Account Account { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Account
{
public int Id { get; set; }
public strig No{ get; set; }
..other fields
public ICollection<AccountCustomer> AccCustomer { get; set; } = new List<AccountCustomer>();
}
public class Customer
{
public int Id { get; set; }
public strig Name{ get; set; }
..other fields
public ICollection<AccountCustomer> AccCustomer { get; set; } = new List<AccountCustomer>();
}
公共类AccountCustomer
{
公共布尔值为{get;set;}
public int AccountId{get;set;}
公共帐户{get;set;}
public int CustomerId{get;set;}
公共客户客户{get;set;}
}
公共类帐户
{
公共int Id{get;set;}
公共strig No{get;set;}
…其他领域
公共ICollection
请让我知道如何做更新…我使用最新的ef 5预览
我的代码:
_context.Set<AccountCustomer>().UpdateLinks(ac => ac.AccountId, account.Id,
ac => ac.CustomerId, account.AccCustomer .Select(ac => ac.CustomerId));
\u context.Set().UpdateLinks(ac=>ac.AccountId,account.Id,
ac=>ac.CustomerId,account.AccCustomer.Select(ac=>ac.CustomerId));
许多更新扩展的代码
删除未选中的项目并将新项目添加到列表中
public static class Extensions
{
public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
{
db.Set<T>().RemoveRange(currentItems.ExceptThat(newItems, getKey));
db.Set<T>().AddRange(newItems.ExceptThat(currentItems, getKey));
}
private static IEnumerable<T> ExceptThat<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
{
return items
.GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
.SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
.Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
.Select(t => t.t.item);
}
}
非常感谢…是否删除所有子项并再次插入?
public class AccountCustomerVM
{
public bool IsMain { get; set; }
public Account Account { get; set; }
public List<int> Customers { get; set; }
}
[HttpPut]
public IActionResult Update(AccountCustomerVM accountCustomerVM)
{
var model = _context.Accounts.Include(x => x.AccCustomer).FirstOrDefault(x => x.Id == accountCustomerVM.Account.Id);
_context.TryUpdateManyToMany(model.AccCustomer, accountCustomerVM.Customers
.Select(x => new AccountCustomer
{
IsMain = accountCustomerVM.IsMain,
CustomerId = x,
AccountId = accountCustomerVM.Account.Id
}), x => x.CustomerId);
_context.SaveChanges();
return Ok();
}