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

我们将现有的MVC6 EF6应用程序移植到核心.

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

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

var model = await _db.Products.FindAsync(vm.Product.ProductId);

            model.Colors.Clear();

            model.Colors =  _db.Colors.Where(x => 
            vm.ColoRSSelected.Contains(x.ColorId)).ToList();

解决方法

这对你有用.

让班级有关系

public class ColorProduct
{
    public int ProductId { get; set; }
    public int ColorId { get; set; }

    public Color Color { get; set; }
    public Product Product { get; set; }
}

将ColorProduct集合添加到Product和Color类

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

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

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.Except(newItems,getKey));
        db.Set<T>().AddRange(newItems.Except(currentItems,getKey));
    }

    public static IEnumerable<T> Except<T,TKey>(this IEnumerable<T> items,IEnumerable<T> other,TKey> getKeyFunc)
    {
        return items
            .GroupJoin(other,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);
    }

使用它看起来像这样

var model = _db.Products
             .Include(x => x.ColorProducts)
             .FirstOrDefault(x => x.ProductId == vm.Product.ProductId);

 _db.TryUpdateManyToMany(model.ColorProducts,vm.ColoRSSelected
 .Select(x => new ColorProduct
 {
     ColorId = x,ProductId = vm.Product.ProductId
 }),x => x.ColorId);

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....