实体框架 – 实体框架核心更新许多对许多

前端之家收集整理的这篇文章主要介绍了实体框架 – 实体框架核心更新许多对许多前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们将现有的MVC6 EF6应用程序移植到核心.

在EF核心中有一个简单的方法来更新多对多的关系吗?

来自EF6的旧代码,我们清除列表并用新数据覆盖它不再有效.

  1. var model = await _db.Products.FindAsync(vm.Product.ProductId);
  2.  
  3. model.Colors.Clear();
  4.  
  5. model.Colors = _db.Colors.Where(x =>
  6. vm.ColoRSSelected.Contains(x.ColorId)).ToList();

解决方法

这对你有用.

让班级有关系

  1. public class ColorProduct
  2. {
  3. public int ProductId { get; set; }
  4. public int ColorId { get; set; }
  5.  
  6. public Color Color { get; set; }
  7. public Product Product { get; set; }
  8. }

将ColorProduct集合添加到Product和Color类

  1. public ICollection<ColorProduct> ColorProducts { get; set; }

然后使用此扩展我删除未选中并将新选择添加到列表中

  1. public static void TryUpdateManyToMany<T,TKey>(this DbContext db,IEnumerable<T> currentItems,IEnumerable<T> newItems,Func<T,TKey> getKey) where T : class
  2. {
  3. db.Set<T>().RemoveRange(currentItems.Except(newItems,getKey));
  4. db.Set<T>().AddRange(newItems.Except(currentItems,getKey));
  5. }
  6.  
  7. public static IEnumerable<T> Except<T,TKey>(this IEnumerable<T> items,IEnumerable<T> other,TKey> getKeyFunc)
  8. {
  9. return items
  10. .GroupJoin(other,getKeyFunc,(item,tempItems) => new { item,tempItems })
  11. .SelectMany(t => t.tempItems.DefaultIfEmpty(),(t,temp) => new { t,temp })
  12. .Where(t => ReferenceEquals(null,t.temp) || t.temp.Equals(default(T)))
  13. .Select(t => t.t.item);
  14. }

使用它看起来像这样

  1. var model = _db.Products
  2. .Include(x => x.ColorProducts)
  3. .FirstOrDefault(x => x.ProductId == vm.Product.ProductId);
  4.  
  5. _db.TryUpdateManyToMany(model.ColorProducts,vm.ColoRSSelected
  6. .Select(x => new ColorProduct
  7. {
  8. ColorId = x,ProductId = vm.Product.ProductId
  9. }),x => x.ColorId);

猜你在找的asp.Net相关文章