views:

1003

answers:

2

Hello,

i'm working with Entity Framework only few weeks. It's great, but how should i add corectly new row with referenced sub-items (tables)?

i tried this procedure

CMS.ShopOrder order = new CMS.ShopOrder();

 order.CreatedOn = DateTime.Now;

 foreach (var item in CMS.CurrentSession.Cart.Items)
 {   
  order.ShopOrderItems.Add(item);
 }

 db.AddToShopOrder(order);  

 int selT = FormatHelper.GetInt32(ddTransport.SelectedValue);
 int selP = FormatHelper.GetInt32(ddTransport.SelectedValue); 

 order.Transportation = db.Transportation.Where(t => t.Id == selT).FirstOrDefault();
 order.Payment = db.Payment.Where(p => p.Id == selP).FirstOrDefault();
 order.Customer = db.Customer.Where(c=>c.Id == CMS.CurrentSession.Customer.Id).FirstOrDefault();

 db.SaveChanges();

but i got error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker. Line 492: base.AddObject("ShopOrder", shopOrder);

Can i add all this records at once?

Thanks a lot.

+2  A: 

It seems that you have a problem with your object context handling. The error indicates that the entity is already assocciated with an object context when you try to add it. I assume you keep some entites alive while performing multiple web request but you create a new object context for every web request. You must detach the entities from the old context and attach them to the new one in order to get the this working.

See the MSDN for a similar problem.

Daniel Brückner
A: 

Thanks danbruc,

the problem was, that i don't detached the object from entityContext when i was adding it to session.

This works:

public CMS.ProductVariant GetProductVariantById(int id)
 {
  ProductVariant pv = null;
  if (id > 0)
  {
   using (db = new CmsEntity())
   {
    pv = db.ProductVariant.Where(v => v.Id == id).FirstOrDefault();
    db.Detach(pv); 
   }
  }
  return pv;
 }
Jan Remunda