实体框架核心更新多对多

问题描述:

我们正在将现有的 MVC6 EF6 应用程序移植到 Core.

We are porting our existing MVC6 EF6 application to Core.

EF Core 中有更新多对多关系的简单方法吗?

Is there a simple method in EF Core to update a many-to-many relationship?

我从 EF6 中清除列表并用新数据覆盖它的旧代码不再有效.

My old code from EF6 where we clear the list and overwrite it with the new data no longer works.

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 集合添加到您的 ProductColor 类:

Add a ColorProduct collection to your Product and Color classes:

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

然后使用我制作的这个扩展来删除未选择的并将新选择的添加到列表中:

Then use this extension I made to remove the unselected and add the newly selected to the list:

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, 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);
}

使用方式如下:

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);