我在 ItemPrice 和 ItemPriceHistory 类之间有一对多的关系,我的映射如下:
public class ItemPrice
{
public long ID {get; set;}
public List<ItemPriceHistory> ItemPriceHistories { get; set; }
public ItemPrice()
{
ItemPriceHistories = new List<ItemPriceHistory>();
}
}
public class ItemPriceHistory
{
public ItemPrice ItemPrice { get; set; }
public long ID {get; set;}
public bool IsCurrent { get; set; }
}
modelBuilder.Entity<ItemPriceHistory>()
.HasRequired(h => h.ItemPrice)
.WithMany(p => p.ItemPriceHistories)
.Map(h => h.MapKey("ItemPrice_ID"));
我正在尝试更新以前的 ItemPriceHistory 条目并尝试添加一个新的 ItemPriceHistory 条目。
var dbItemPrice = repo.Std.Get<ItemPrice>()
.SingleOrDefault(c => c.ID == id);
if (dbItemPrice == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
//query for matching ItemPriceHistory
var dbPriceHistories = repo.Std.Get<ItemPriceHistory>()
.Include(h=>h.ItemPrice, repo.Std)
.Where(h => h.ItemPrice.ID == ItemPrice.ID)
.OrderByDescending(h => h.ModifiedDate);
#region new history entry
var newHistoryEntry = new ItemPriceHistory();
newHistoryEntry.IsCurrent = true;
newHistoryEntry.ItemPrice = dbItemPrice;
//copy the current pirce list and update it with new history entry
var currentPriceHistoryList = dbPriceHistories.ToList();
currentPriceHistoryList.ForEach(h => { h.IsCurrent = false; });
currentPriceHistoryList.Add(newHistoryEntry);
//new price list
var newHistoryList = new List<ItemPriceHistory>();
currentPriceHistoryList.ForEach(h => newHistoryList.Add(new ItemPriceHistory
{
ItemPrice = h.ItemPrice,
IsCurrent = h.IsCurrent,
}
));
#endregion
//delete current price histories
dbItemPrice.ItemPriceHistories.Clear();
// add histories to database
newHistoryList.ForEach(h => dbItemPrice.ItemPriceHistories.Add(h));
Context.SaveChanges();
当它调用 SaveChanges() 时,我收到以下错误:
{“保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过公开可以更轻松地在保存时处理异常实体类型中的外键属性。有关详细信息,请参阅 InnerException。"}
InnerException: {“来自‘ItemPriceHistory_ItemPrice’AssociationSet 的关系处于‘已删除’状态。给定多重约束,相应的‘ItemPriceHistory_ItemPrice_Source’也必须处于‘已删除’状态。”}
我不想删除我的ItemPrice_Source
. 我只想删除当前ItemPriceHistories
并更新以前的ItemPriceHistories
并添加新ItemPriceHistory
条目。如何安全地更新ItemPriceHistory
条目以及新ItemPriceHistory
条目?
谢谢!