views:

257

answers:

2

Scenario: Entity Framework 4 , POCO templates and Master Detail relation.

Lets say I have a master type like this:

//partial implementation of master entity
partial class Master
{
    public void AddDetail(x,y,z)
    {
        var detail = new Detail()
        {
           X = x,
           Y = y,
           Z = z,
        };

        //add the detail to the master
        this.Details.Add(detail);
    }
}

If I then add a master instance to my context and commit, the details will not be saved:

var masterObject = new Master();
masterObject.AddDetail(1,2,3);
myContext.MasterSet.AddObject(masterObject);

Is there any way to make the details to be persisted by reachabillity when using POCO templates? Or any other way? the Details collection in the Master entity is a FixUpCollection, so it ought to track the changes IMO.

So, any ideas how to make this work W/O killing the POCO'ness too much?

A: 
Dave Swersky
The first suggestion violates POCO pretty badly.And the second suggestion doesn't solve the problem of changed details.Repositories are supposed to store aggregate roots, you are not supposed to have one for sub objects in an aggregate.So solving this in the repository would have to involve checking if a detail is new or already persistent etc..
Roger Alsing
A: 

I found the solution.

I simply have to pass SaveOptions.DetectChangesBeforeSave like so:

context.SaveChanges(SaveOptions.DetectChangesBeforeSave);

This allows me to add detail objects to the master object w/o attaching each individual detail to the context.

Roger Alsing