【发布时间】:2011-05-10 21:41:17
【问题描述】:
我有以下数据库设置:-
Person Table
Hobby Table
Game Table
GameInfo Table
人物 [1 - M] 爱好 [1 - M] 游戏 [M - 1] 游戏信息
Game 只是从Hobby 到GameInfo 的连接
我遇到了一个问题,我将获取具有Collection<Game> 的Person 并添加到此集合中(即我只是在更新链接,不想插入新的GameInfo)。
在调用SaveChanges() 时,EntityFramework 将插入链接以及插入新的GameInfo,这不是我想要的结果。
我查看了 Entry().State 等,但问题是我处理 Person 更新的位置超出了上下文。
我基本上是在获取一个Person 创建一个新的Game,其ID 我知道已经存在,然后调用SaveChanges() 并希望它只会插入Game 表,而不是GameInfo 表
编辑 1:代码示例 - 有点
public void Save(Profile profile)
{
using (GDContext context = GetContext())
{
DataProfile dataProfile = context.Profiles.Single(u => u.ProfileId == profile.Id);
ProfileHandler.HandleDataModelChanges(dataProfile, profile);
context.SaveChanges();
}
}
public override void HandleDataModelChanges(DataProfile dataModel, Profile model)
{
dataModel.ProfileId = model.Id;
dataModel.FirstName = model.FirstName;
dataModel.LastName = model.LastName;
dataModel.DateOfBirth = model.DateOfBirth;
dataModel.Email = model.Email;
foreach(var hobby in model.Hobbies)
{
DataHobby dataHobby = dataModel.Hobbies.SingleOrDefault(p => p.HobbyId == hobby.HobbyId);
if (dataHobby == null)
{
dataHobby = new DataHobby();
}
HobbyHandler.HandleDataModelChanges(dataHobby, hobby);
}
}
public override void HandleDataModelChanges(DataHobby dataModel, Hobby model)
{
dataModel.HobbyId = model.Id;
HandleGames(dataModel, model);
HandleCrafts(dataModel, model);
HandleCollections(dataModel, model);
}
private void HandleGames(DataHobby dataModel, Hobby model)
{
IEnumerable<DataGame> gamesToRemove = dataModel.Games.Where(g => !model.Games.Any(ds => ds.Id == g.GameId)).ToArray();
foreach (var game in gamesToRemove)
{
dataModel.Games.Remove(game);
}
foreach (var game in model.Games)
{
if (!dataModel.Games.Any(e => e.GameId == game.Id))
{
DataGame dataGame = new DataGame();
dataGame.GameId = game.Id;
dataGame.GameName = game.Name;
dataModel.Games.Add(dataGame);
}
}
}
编辑 2 - 上下文配置
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.AutoDetectChangesEnabled = true;
public GameInfoConfiguration()
{
HasKey(x => x.GameId);
ToTable("GameData");
}
public PersonConfiguration()
{
HasKey(x => x.PersonId);
ToTable("Person");
}
public HobbyConfiguration()
{
HasKey(x => x.HobbyId);
HasRequired(x => x.Person).WithMany(x => x.Hobbies);
HasMany(x => x.Games).WithMany(g => g.Hobbies).Map(x => x.MapLeftKey("HobbieId").MapRightKey("GameId").ToTable("PersonGame"));
ToTable("HobbyGame");
}
【问题讨论】:
-
我认为显示一些代码 sn-p 将使场景更加清晰,然后尝试解释它。显示如何创建/检索实体以及如何处理上下文 + 插入实体的小代码示例。
标签: c# entity-framework entity-framework-4