Entity Framework : updating one-many relationships for an entity's child collection
Consider an application dealing with houses and pictures. An entity named House
has a 1:n relationship to HousePicture
.
The application allows the user to create and edit a House
, and add/remove HousePictures
.
[HttpPost]
public ActionMethod Edit(House h)
{
//get an attached entity from the DB first.
House original = db.Houses.SingleOrDefault(x=>x.ID==h.ID);
UpdateModel(original);
//collect all the uploaded pictures.
original.HousePictures = GatherPicturesFromForm();
db.SaveChanges();
// the changes for the House are saved,
//but child collection Pictures are not.
}
How do you go about updating - adding new & deleting - the child collection when recreating the child collection from scratch?
Add()
orAttach()
for each child in the collection?- In what sequence do you need to Add or Attach the parent entity vs. the child collection?
- How to go about detecting the children to remove? Is this a feature of EF4 where deletes happen automatically by the framework, or does the developer need to write this logic?
When adding more than one
HousePicture
, its ID == 0. The entity has the primary key in SQL Server has an auto-assigned PK ofint IDENTITY(1,1)
. This becomes a problem because EF4 thinks that 2+ child have the same ID.What are your recommendations on saving child col开发者_如何学Pythonlections using Entity Framework 4?
- Any other suggestions on making the persistence of 1:n collections easier when updating/adding/deleting?
In EF just add new objects to a collection and they'll automatically be persisted to the database with the correct foreign key values.
original.HousePictures.AddRange(GatherPicturesFromForm());
精彩评论