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?