【发布时间】:2017-01-24 22:55:00
【问题描述】:
我在更新特定实体图时遇到问题,其中包含具有两个相同类型导航属性的实体(同一个表的两个外键)
因此,产品可以参与促销(一对多),并且促销有一套产品,用作礼物(多对多)。如果有与产品相关的促销,您购买一种产品并免费获得另一种(或多种)产品。
这是我的班级结构:
public class Product
{
public int Id { get; set; }
public int? PromoItemId { get; set; }
public virtual PromoItem PromoItem { get; set; }
public virtual ICollection<PromoItem> AddedToPromoItems { get; set; }
}
public class PromoItem
{
public int Id { get; set; }
[InverseProperty("PromoItem")]
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Product> AddedProducts { get; set; }
}
我正在尝试使用单个 EF 上下文更新 PromoItem 实体,包括 Products 和 AdditionalProducts 集合:
public void Update(PromoItem entity)
{
using (var context = new MyContext())
{
// original entity
var originalEntity = context.PromoItems
.Include(p => p.Products)
.Include(p => p.AddedProducts)
.Single(p => p.Id == entity.Id);
// update products (one to many)
var productIds = entity.Products.Select(ap => ap.Id).ToList(); // get products ids
var products = context.Products // load products from DB
.Where(p => productIds.Contains(p.Id))
.ToList();
originalEntity.Products.UpdateFrom(products, context); // here is Add, Remove etc to collection
// update added products (many to many)
// *********************
// one of the product here was removed from Products collection, so it already attached to the context and has "Deleted" state!
// *********************
var addedProductIds = entity.AddedProducts.Select(ap => ap.Id).ToList(); // get products ids
var addedProducts = context.Products // load products from DB
.Where(p => addedProductIds.Contains(p.Id))
.ToList();
originalEntity.AddedProducts = addedProducts; // assign many to many collection
// update entity
context.Update(originalEntity, entity);
// save changes
context.SaveChanges(); // here I got an error "Adding a relationship with an entity which is in the Deleted state is not allowed."
}
}
当同一产品在两个集合中时会出现问题。假设我想将它从一个集合中删除并添加到另一个集合中。我只需要更新基本实体及其关联(而不是产品本身)。 如何在同一数据库上下文中两次加载具有不同状态的同一实体?
【问题讨论】:
标签: c# entity-framework