Jerry
Jerry

Reputation: 6557

How to attach object to existing property using Entity Framework

I have a property that contains a list from an entity in my model. I want to add an item to this list but when I do, it's added as detached. How can I add this object as attached?

using (var db = new fsEntities())
{
   var list = db.Products.Where(x => x.ID == 1).ToList();
   var p = new Product { Description = "New Item", Amount = 14};
   list.Add(p);   //the new item EntityState is detached
}

I know I can do this, db.AddToProducts(p), but in my scenario I want to add the object to the existing property with it's EntityState as attached, then later perform a SaveChanges if necessary.

How can I do this?

Upvotes: 0

Views: 316

Answers (1)

Eranga
Eranga

Reputation: 32437

You can attach the entity. This will be added to the context with Unchanged state.

using (var db = new fsEntities())
{
   var list = db.Products.Where(x => x.ID == 1).ToList();
   var p = new Product { Description = "New Item", Amount = 14};

   db.Attach(p);

   list.Add(p);   //the new item EntityState is detached
}

Upvotes: 1

Related Questions