开发者

Is there an easier way to assign relationships to new objects in Entity Framework?

开发者 https://www.devze.com 2022-12-21 13:04 出处:网络
In my example, I\'m trying to create a new object which has references to existing objects.I\'m finding myself having to retrieve complete objects from the database in order to reference them from my

In my example, I'm trying to create a new object which has references to existing objects. I'm finding myself having to retrieve complete objects from the database in order to reference them from my new object.

Apologies for any small errors in the code - I'm working from memory - I don't have my code with me.

My ViewModel contains the object itself, my two reference Ids, and a SelectList of the referenced object so I can bind to a dropdown:

public class GameEditViewModel
{
    public Game MyGame { get; set; }
    public int HomeTeamId { get; set; }
    public int AwayTeamId { get; set; }
    public SelectList<Team> { get;开发者_如何学运维 set; }
}

I'm setting and getting everything perfectly fine, and the object is fully populated when I get it back, but the problem comes when I try to save this new Game:

public Game AddGame(GameEditViewModel gameToSave)
{
    gameToSave.MyGame.HomeTeam = 
        context.GetObjectByKey(new EntityKey(context.DefaultContainerName+".Team", "Id", gameToSave.HomeTeamId)) as Team;
    context.Attach(gameToSave.MyGame.HomeTeam);  // I think I needed this line
    gameToSave.MyGame.AwayTeam = 
        context.GetObjectByKey(new EntityKey(context.DefaultContainerName+".Team", "Id", gameToSave.AwayTeamId)) as Team;
    context.Attach(gameToSave.MyGame.AwayTeam);

    context.AddToGame(MyGame);
    context.SaveChanges();
}

You see the problem here - I'm doing two extra database queries to retrieve models so I can bind to them. Really, I should only need the Id.

If I just set the HomeTeam.Id and AwayTeam.Id properties, the context thinks I'm adding a new record and complains that all the references required for the Team object are not set.

I assume there's a better/more efficient way to do this, but I'm pretty new to EF. Can anyone enlighten me?


This doesn't require database roundtrip:

gameToSave.MyGame.HomeTeamReference.EntityKey = new EntityKey(context.DefaultContainerName+".Team", "Id", gameToSave.HomeTeamId)


You can also do this, which is prettier imo:

public Game AddGame(GameEditViewModel gameToSave)
{
    gameToSave.MyGame.HomeTeam = new Team { Id = gameToSave.HomeTeamId };
    gameToSave.MyGame.AwayTeam = new Team { Id = gameToSave.AwayTeamId };

    context.AddToGame(MyGame);
    context.SaveChanges();
}
0

精彩评论

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

关注公众号