I am trying to update an whole entity object with relations in database in entity framework , and without success.
I am trying to do something like this:
var objectToUpdate = DAL.GetProduct(id);
// then I have collection of Comments related to this product.
// and I want to update th whole collection
objectToUpdate.Comments.Clear();
foreach(var newComment in comments){
objectToUpdate.Comments.Add(newComment);
}
What I am getting in database is duplication of all related to my products comments.
Please suggest how to update related Entities properly.
Thanks.
If you want to update a relationship between
objectToUpdateand a collection of comments which are already existing in the database you need to attach the comments to context before you add them to theCommentscollection of yourobjectToUpdate. Otherwise EF will create new comment rows in the database: