Christopher
Christopher

Reputation: 10627

Are child objects supposed to update automatically in Entity Framework 4 Code-First?

I've got this Venue object:

public class Venue
{
    public int Id { get; set; }

    [Required]
    [MaxLength(512)]
    public string Name { get; set; }

    public string Description { get; set; }

    [Required]
    [Display(Name = "Venue Type")]
    public int VenueTypeId { get; set; }
    public virtual VenueType VenueType { get; set; }

    [Required]
    [Display(Name = "Company")]
    public int CompanyId { get; set; }
    public virtual Company Company { get; set; }

    public virtual ICollection<VenuePart> VenueParts { get; set; }
}

As you can see, it has a collection of VenueParts. I send the Venue to the view, and output the collection of VenueParts as a table of textboxes. This gets posted back to Edit(VenueDetailsViewModel venueDetailsViewModel). Using the debugger, I can verify that my change are in the VenueParts collection, so I think we're good on binding.

My controller tries to update the Venue. It succeeds on the properties directly on the object, such as Name. But, unless I loop through the collection, it does not update those objects. Is that typical behavior?

unitOfWork.VenueRepository.Update(venueDetailsViewModel.Venue);
// Should this loop be necessary?
foreach (var venuePart in venueDetailsViewModel.Venue.VenueParts)
{
    unitOfWork.VenuePartRepository.Update(venuePart);
}
unitOfWork.Save();

At the moment, I'm not even worried about handling new stuff in the list or things that vanished from the list (although that is what I am tackling next). For my first step here, I just want to get the list updated. Is it necessary to loop through the collection and update each individual object? If I don't do this, they don't save. But it seems like they ought to without my loop. Are my expectations too high or am I doing something wrong?

My repository and unitOfWork objects are patterned after this tutorial if you are curious what that code looks like.

Upvotes: 0

Views: 1230

Answers (1)

Eranga
Eranga

Reputation: 32437

That is because unitOfWork.VenueRepository.Update(venueDetailsViewModel.Venue); will attach the object graph in Unchanged state and only change the venue as Modified. One alternative would be to move the foreach loop to the VenuePartRepository.Update method.

If you allow elements of VenueParts to be added or removed from the UI you will have a hard time applying the changes. If this is the case you will have to load the collection in the database and compare that with the changes coming in. Then manually change the states of VenuePart to Added or Deleted.

Upvotes: 1

Related Questions