4
It is possible to update the Collection
of an entity with one-to-many
through his navigation property
?
public class Foo
{
public virtual IList<Bar> Bars {get; set;}
public int FooID { get; set; }
}
public void UpdateFoo(Foo foo)
{
dbContext.Set<Foo>.Attach(foo);
dbContext.Entry(foo).State = EntityState.Modified;
}
The behavior of EF
is to add the objects of foo.Bars
table, without removing records that do not exist in the collection. The alternative solution I found was to perform a dbSet.RemoveRange
objects not existing in foo.Bars
to delete them from the database.
What is the most appropriate way to update a Collection?
EDIT-----------------
Analyzing this post by Daniel Simmons, looks like the version 6.x
of entity framework
does not support this resource. The behavior performed by ORM
is to modify the value of foreign keys to null
, not deleting the record.
Is there any recommended approach to perform this operation?
Here always gives this Exception when mark as modified: Saving or Accepting changes failed because more than one Entity of type '' have the same Primary key value. Ensure that explicitly set Primary key values are Unique. Ensure that database-generated Primary Keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First Configuration. Use the 'Hasdatabasegeneratedoption" Fluent API or 'Databasegeneratedattribute' for Code First Configuration. Any idea of what?
– Eduardo Moreira
I managed to fix it. It was a sum of wrong things. Anyway your answer saved my skin, thank you very much!
– Eduardo Moreira