开发者

Entity Framework Partial Classes Instantiate by Id / Primary Key

I'm using Entity Framework 4.1. I have a normal model .edmx which maps a Match class to a 'Match' database table and this can be accessed as normal using EF.

However I require custom properties methods for the Match so I extended this using a partial class and I can add my properties etc.

All of this works fine, however I just can't find out how to instantiate an instance of my partial match class by its primary key / id. i.e so I can pass the Id into the constructor and have the object populated with all of its data from the database.

I know we can do the following to populate from calling code:

 public Match PopulateforMatchId(int matchId)
    {
        var match = (from m in _db.Matches
                         .Include("TeamA")
                         .Include("TeamB")
                         .Include("Season")
                         .Include("Season.Competition")
                     where m.Match_ID == matchId
                     select m).FirstOrDefault();

        return match;

    }

However this is not what I need as this is not self contained within the partial class itself, I need it to populate itself, as other properties in 开发者_如何学JAVAthe partial class rely on the object itself having its data in place before they can be calculated.

Anyone have any ideas how i can do this?

Thanks

Kevin


This is wrong way to use Entity framework. Entity framework is not suitable for easy populating existing object. Moreover it demands that entity has internal dependency on the EF context.

How to probably make it work (but I definitely not recommend it):

public Match(int matchId) 
{
    // You called constructor yourselves = you have unproxied entity without
    // dynamic change tracking and without lazy loading

    Id = matchId;

    // I'm not sure if this is possible in entity constructor but generally it should work

    // Get context somewhere - service locator pattern
    ObjectContext context = ContextProvider.GetCurrent();
    context.Matches.Attach(this);
    context.Refresh(RefreshMode.StoreWins, this);
    // Now you should have populated Match entity itself but not its navigation properties

    // To populate relations you must call separate query for each of them because `Include`
    // is possible only when the entity is created and loaded by EF and lazy loading is off
    // in this case

    context.LoadProperty(this, m => m.TeamA);
    context.LoadProperty(this, m => m.TeamB);

    Season = (from s in context.Seasons.Include("Competition")
              select s).ToList();      
}

This is also the example of wrong constructor - constructor should not take such heavy logic. It should be responsibility of some other initialization method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜