entity-framework - Entity Framework 核心更新多对多

标签 entity-framework asp.net-core

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

EF Core 中是否有一种简单的方法来更新多对多关系?

我从 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收藏到您的 ProductColor类:
 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, 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);

关于entity-framework - Entity Framework 核心更新多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42993860/

相关文章:

c# - 具有 "Group By"和/或 "Order by"的 Entity Framework

caching - C# IUnitOfWork、IRepository 和 IMemoryCache [ASP.Net Core]

c# - 如何在 Asp Net Core RC1 MVC 中使用 token 身份验证添加 "ApiController"

asp.net - 在本地解析Docker主机名时HttpClient花费太多时间

c# - cookie 过期后如何返回 401 状态而不是 302 重定向?

c# - 是否存在用于生成 WCF 服务以为 self 跟踪实体提供获取和保存的 T4 模板?

c# - EF 递归层次结构

.net - EF Code First 和大型模型的性能

c# - 为什么无法检查模型兼容性?

c# - 服务器端渲染。 Web API 和 Angular 2