views:

242

answers:

1

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() or Attach() 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 of int IDENTITY(1,1). This becomes a problem because EF4 thinks that 2+ child have the same ID.

  • What are your recommendations on saving child collections using Entity Framework 4?

  • Any other suggestions on making the persistence of 1:n collections easier when updating/adding/deleting?
A: 

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());

Paul Mendoza
@Paul: thanks... does this include deletes when child objects in the database don't exist in the 'new' set?
p.campbell
One would think it would especially if the OI foreign key requires that relationship on the child object.
Paul Mendoza
@Paul: unfortunately `EntityCollection<T>` doesn't have an `AddRange()`
p.campbell