Friday, 15 May 2015

c# - Error occurring when Entity State is modified -



c# - Error occurring when Entity State is modified -

i trying test wcf web service shopping cart. method below receives list of cartline , subtracts products added shopping cart database. sends message either processed or if inventory insufficient order cancellation message.

public string deliver(list<cartline> cartline) { string strout = null; startpurchase(); if (convert.toboolean(httpcontext.current.session["transactionstarted"])) { //traverse cart line (int = 0; < cartline.count; i++) { //for each product in cart line decrease inventory if (cartline[i].product.stock > 0) { //here decreasing inventory (cartline[i].product.stock) -= (cartline[i].quantity); //advice entity has changed db.entry(cartline[i].product).state = entitystate.modified; //offending line db.savechanges(); strout = "order processed!"; } else { strout = "order cancelled, stock missing!"; } } homecoming strout; } else { homecoming m_cartsessionnotstartedstr; } }

all things work fine if add together same kind of product cart. mix products, however, error:

attaching entity of type 'x’ failed because entity of same type has same primary key value. can happen when using 'attach' method or setting state of entity 'unchanged' or 'modified' if entities in graph have conflicting key values. may because entities new , have not yet received database-generated key values. in case utilize 'add' method or 'added' entity state track graph , set state of non-new entities 'unchanged' or 'modified' appropriate.

this error occurs @ point when saving changes (see offending line above). while understand should attach entity not sure how proceed in case when list of product lines.

can help?

thank you

you must check if entity same key tracked context or not. if entity tracked, modify entity instead of attaching 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();

c# asp.net-mvc entity-framework

No comments:

Post a Comment