在编辑多对多关系之间的关系表时,标题出现错误。它不会在表上重复,因此我尝试删除行,然后创建新的行,但是没有用。
public void Update(ThermoformProduct entity, int[] thermoformCategoryIds)
{
using (var context = new ShopContext())
{
var product = context.ThermoformProducts
.Include(i => i.ThermoformProductCategories)
.FirstOrDefault(i => i.ProductId == entity.ProductId);
if (product != null)
{
product.Code = entity.Code;
product.Culture = entity.Culture;
product.Renk = entity.Renk;
product.UstGenislik = entity.UstGenislik;
product.UstCap = entity.UstCap;
product.AltCap = entity.AltCap;
product.TbCap = entity.TbCap;
product.Yukseklik = entity.Yukseklik;
product.Hacim = entity.Hacim;
product.TamHacim = entity.TamHacim;
product.Baski = entity.Baski;
product.SosisIciAdet = entity.SosisIciAdet;
product.KoliIciAdet = entity.KoliIciAdet;
product.ImageUrl = entity.ImageUrl;
product.ThermoformProductCategories.RemoveAll(s=>s.ProductId == product.ProductId);
product.ThermoformProductCategories = thermoformCategoryIds.Select(catid => new ThermoformProductCategory()
{
ProductId = product.ProductId,
ThermoformProduct = product,
CategoryId = catid,
ThermoformCategory = context.ThermoformCategories.Where(i => i.CategoryId == catid).FirstOrDefault()
}).ToList();
context.SaveChanges();
}
}
}
EF无法使用相同的主键跟踪实体类型的两个不同实例。您已包括相关ThermoformProductCategory
实体,因此上下文会对其进行跟踪。当您删除它们时,它们将从该ThermoformProductCategories
产品的属性中清除,但是它们并未从上下文中删除,并且仍在跟踪中。最后,当您创建的新列表时ThermoformProductCategory
,某些新主键与先前的主键匹配(上下文中已经存在)
由于您是在重新创建整个列表,因此无需首先获取相关实体。只需分配一个新列表,EF就会替换整个相关实体列表-
var product = context.ThermoformProducts.FirstOrDefault(i => i.ProductId == entity.ProductId);
if (product != null)
{
// set all the properties
product.ThermoformProductCategories = thermoformCategoryIds.Select(catid => new ThermoformProductCategory()
{
ProductId = product.ProductId,
CategoryId = catid
}).ToList();
context.SaveChanges();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句