我在尝试保存作为父对象外键的实体时遇到问题..
我有一个 amazonProduct 实体。还有一个 AmazonCompetitivePrice 实体,它是 amazonProduct 上的虚拟列表,如下所示:
public class AmazonProduct
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int ASIN
public virtual IList<AmazonProductCompetitivePrice> amazonProductCompetitivePrices = new List<AmazonProductCompetitivePrice>();
}
所以我有一个从数据库中检索到的 AmazonProduct,然后将新的 AmazonProductCompetitivePrice 添加到 amazonProduct。
但是当我尝试保存它时,出现以下错误:
Violation of PRIMARY KEY constraint 'PK_dbo.AmazonProducts'. Cannot insert duplicate key in object 'dbo.AmazonProducts'.\r\nThe statement has been terminated
看起来它没有意识到我的 AmazonProduct 已经在数据库中,并且它试图保存一个新的但主键已经存在!
我使用 Fluent API 来映射外键,如下所示:
modelBuilder.Entity<AmazonProduct>()
.HasMany(pl => pl.AmazonProductCompetitivePrices)
.WithOptional(p => p.AmazonProduct)
.Map(c => c.MapKey("ASIN"));
有人知道这是怎么回事吗?
提前致谢!
编辑: 对象检索:
using (var uow = new UnitOfWorkInventory())
{
using (var amazRepo = new AmazonProductRepository(uow))
{
return amazRepo.FindByAsin(ASIN);
}
}
public AmazonProduct FindByAsin(string asin)
{
return context.AmazonProducts.Include(x => x.AmazonLowestOfferListings).Include(x => x.AmazonMyPrices).Include(x => x.AmazonProductCompetitivePrices).SingleOrDefault(x => x.ASIN == asin);
}
这让我得到了 AmazonProduct.. 然后保存:
using (var uow = new UnitOfWorkInventory())
{
using (var amazonRepo = new AmazonProductCompetitivePriceRepository(uow))
{
amazonProductCompetitivePrice.AmazonProduct = amazonProduct;
amazonRepo.InsertOrUpdate(amazonProductCompetitivePrice);
}
uow.Commit();
}
public void InsertOrUpdate(AmazonProductCompetitivePrice amazonProductCompetitivePrice)
{
if (amazonProductCompetitivePrice.Id == default(int))
{
// New entity
context.AmazonProductCompetitivePrices.Add(amazonProductCompetitivePrice);
}
else
{
// Existing entity
context.Entry(amazonProductCompetitivePrice).State = EntityState.Modified;
}
}
这就是一切......感谢您的帮助!!
最佳答案
这一行:
amazonProductCompetitivePrice.AmazonProduct = amazonProduct;
将 amazonProduct
实例隐式添加到上下文中。因为该实例是使用不同的上下文实例检索的,当前实例认为它是新的 AmazonProduct
。你应该附加它,像这样:
if (amazonProductCompetitivePrice.AmazonProduct != null && amazonProductCompetitivePrice.AmazonProduct.Id != 0)
{
context.Entry(amazonProductCompetitivePrice.AmazonProduct).State = EntityState.Unchanged;
}
另一种方法:您可以只为 amazonProductCompetitivePrice
设置外键属性,而不是导航属性。
关于c# - 违反 PRIMARY KEY 约束 'PK_dbo.AmazonProducts' 。无法在对象中插入重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237636/