修改实体状态时发生错误 [英] Error occurring when Entity State is modified
问题描述
我正在尝试使用购物车来测试WCF Web服务。以下方法基本上收到CartLine列表,并从数据库中减去添加到购物车中的所有产品。然后,它发送一个消息被处理或如果库存不足,那么订单取消消息。
I am trying to test a WCF Web Service with a shopping cart. The method below basically receives a list of CartLine and subtracts all the products added to the shopping cart from the database. Then it sends a message either processed or if the inventory is insufficient then an order cancellation message.
public string Deliver(List<CartLine> cartLine)
{
string strOut = null;
StartPurchase();
if (Convert.ToBoolean(HttpContext.Current.Session["TransactionStarted"]))
{
//Traverse the cart line
for (int i = 0; i < cartLine.Count; i++)
{
//for each product in the cart line decrease inventory
if (cartLine[i].Product.Stock > 0)
{
//here decreasing inventory
(cartLine[i].Product.Stock) -= (cartLine[i].Quantity);
//Advice that entity has changed
db.Entry(cartLine[i].Product).State = EntityState.Modified; //offending line
db.SaveChanges();
strOut = "Order Processed!";
}
else
{
strOut = "Order cancelled, Stock missing!";
}
}
return strOut;
}
else
{
return m_cartSessionNotStartedStr;
}
}
如果我添加同样的产品到购物车。然而,一旦混合了产品,那么我会收到这个错误:
All things work fine if I add the same kind of product to the cart. As soon as I mix products, however, then I get this error:
连接类型X的实体失败,因为已经有同一类型的另一个实体具有相同的主键值。当使用附加方法或将实体的状态设置为不变或修改时,如果图中的任何实体具有冲突的键值,则可能会发生这种情况。这可能是因为一些实体是新的,并且尚未接收到数据库生成的键值。在这种情况下,使用添加方法或已添加实体状态来跟踪图形,然后根据需要将非新实体的状态设置为不变或修改。
保存更改时出现此错误(请参阅上面的违规行)。虽然我明白,我应该附上实体,我不知道在这种情况下如果它是一个产品线列表,如何进行。
This error occurs at the point when saving the changes (see offending line above). While I understand that I should attach the entity I am not sure how to proceed in this case when it is a list of product lines.
任何人都可以帮助?
谢谢
推荐答案
您必须检查具有相同密钥的实体是否已经被上下文跟踪了。如果实体跟踪,修改该实体,而不是附加当前的实体:
You must check if an entity with the same key is already tracked by the context or not. If entity tracked, modify that entity instead of attaching the current one:
var trackedEntity = context.Products.Find(cartLine[i].Product.Id);
context.Entry(trackedEntity).CurrentValues.SetValues(cartLine[i].Product);
context.Entry(trackedEntity).State = EntityState.Modified;
context.SaveChanges();
这篇关于修改实体状态时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!