实体框架 – 实体框架核心更新许多对许多
发布时间:2020-05-22 19:17:59 所属栏目:asp.Net 来源:互联网
导读:我们将现有的MVC6 EF6应用程序移植到核心. 在EF核心中有一个简单的方法来更新多对多的关系吗? 来自EF6的旧代码,我们清除列表并用新数据覆盖它不再有效. var model = await _db.Products.FindAsync(vm.Product.ProductId); model.Colors.Clear(); model.C
|
我们将现有的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); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp-classic – 如何在经典ASP中遍历集合?
- asp.net-mvc – MVC 4,复选框列表和我
- asp.net-mvc-3 – 如何模拟查询字符串
- asp.net-mvc – 如何给Razor MVC中的共享布局模型?
- asp.net-mvc – 一个ASP.NET MVC验证器,用于确保至少选中一
- asp.net – 在Visual Studio 2012中创建控制器时出错
- asp.net-mvc – ASP.NET MVC:多个项目错误
- ASP.NET MVC 4软件包在mono v3下不工作
- asp.net-mvc-3 – 动态加载部分视图
- asp.net-mvc – ASP.Net MVC4根cshtml和“不继承’System.W
推荐文章
站长推荐
- asp.net-mvc – 缺少webpages_UsersInRoles
- asp.net-mvc-4 – 如何在asp.net mvc应用程序中使
- asp.net – 动画gif不动画提交
- asp.net-mvc – Asp.net内核MVC post参数始终为n
- 如何合理地构建我的ASP.NET MVC 2项目与区域
- file-upload – 增加Kestrel的上传请求长度限制
- ASP.Net 4.0中可用的新功能是什么?
- 将ASP.NET验证与JQuery相结合的优雅方式
- asp.net – Web.config自定义错误模式冲突
- asp.net-mvc – 使用linq2sql在c#mvc中不显示所选
热点阅读
