My current problem seems like a mutant version of what I ran into a few months ago (see: Problems updating w/ EF4 repo & MVC2 - can't update many-to-many graph). I can create a new Game-Platform graph, but I can't edit the Platform side of an existing graph. So, I can't add/remove Platforms from the relationship.
I'm using AutoMapper to map the incoming data to entities. I'm then manually attaching the Game entity to the ObjectContext in my repository, and manually setting its EntityState based on whether I'm creating a new entity graph, or updating an existing one. Here's my current setup:
AutoMapper mapping:
Mapper.CreateMap<AdminGameEditModel, Game>()
.BeforeMap((s, d) =>
{
foreach (var platId in s.PlatformIDs)
{
Platform newPlat = _gameRepository.GetPlatform(platId);
d.Platforms.Add(newPlat);
}
})
.ForMember(dest => dest.BoxArtPath, opt => opt.Ignore())
.ForMember(dest => dest.IndexImagePath, opt => opt.Ignore())
.ForMember(dest => dest.Cons, opt => opt.MapFrom(src => String.Join("|", src.Cons)))
.ForMember(dest => dest.Pros, opt => opt.MapFrom(src => String.Join("|", src.Pros)))
.ForMember(dest => dest.LastModified, opt => opt.UseValue(DateTime.Now))
.ForMember(dest => dest.Platforms, opt => opt.Ignore());
The GetPlatform method of my repo:
public Platform GetPlatform(int id)
{
Platform plat = _siteDB.Platforms.FirstOrDefault(pl => pl.PlatformID == id);
_siteDB.Detach(plat);
return plat;
}
And my SaveGame method:
public void SaveGame(Game game)
{
_siteDB.Games.Attach(game);
if (game.GameID > 0)
{
_siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);
}
else
{
_siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Added);
}
_siteDB.SaveChanges();
}
My only thought is that I need to Remove()
the Platforms of the existing Game entity. I'm not sure how to do that gracefully with my current setup as I already have an incoming fresh Game entity being sent to SaveGame()
that has the new list of Platforms. I feel like there has to be a better, more graceful way of doing things.
So, any ideas? I'm trying to keep references to my UI (view/edit models and the like) from creeping into my domain layer, so I don't want my repo to deal with my AdminGameEditModel
directly.