0

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?

1
  • Its usual when you are adding new object - it is in Detached state by default. Only in Insert method that generates for you EntityState changed to Added. Commented Jan 28, 2012 at 0:11

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, my problem was getting the new item's entity state to be "added" instead of "detached". This does what I need it to do. db.Products.AddObject(item); list.Add(item);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.