开发者

Persisting details in Master Detail relation EF4 POCO

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 u开发者_C百科sing 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?


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.


You could:

Add a constructor to your entities that accepts a Context, which is saved by reference in a private field. Your AddDetail function could then check the private _context field, and if it refers to an instantiated Context, add the Details to the context after the Master record is saved.

However...

This might not be the best pattern, as it violates the Single Responsibility Principle. I think it would be better to use a Repository pattern, and have the Repository commit the unsaved Details. Here is a great article on implementing the Repository Pattern in Entity Framework 4.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜