views:

41

answers:

2

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?

+3  A: 

This doesn't require database roundtrip:

gameToSave.MyGame.HomeTeamReference.EntityKey = new EntityKey(context.DefaultContainerName+".Team", "Id", gameToSave.HomeTeamId)
LukLed
Wow, really? Man... how did I miss that...?
Damovisa
@Damovisa: Sorry, but I don't know:)
LukLed
I think I just assumed that it did. I'll verify when I get home, but I'm sure you're right. Thanks :)
Damovisa
A: 

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();
}