【发布时间】:2015-10-18 10:55:56
【问题描述】:
我遇到了 Entity Framework 6.1.3 CodeFirst 多对多关系的问题。我的模型基本上是这样的:
class Schedule
{
int Id { get; set; }
}
class Contest
{
int Id { get; set; }
ICollection<Schedule> GameSchedules { get; set; }
}
我的上下文供参考:
class MyContext
{
MyContext() : base("name=DefaultConnection")
{
// no lazy loading for us
this.Configuration.LazyLoadingEnabled = false;
// do not auto detect changes for me
this.Configuration.AutoDetectChangesEnabled = false;
// we don't want our stuff to be wrapped in proxies
this.Configuration.ProxyCreationEnabled = false;
}
}
Entity Farmework CodeFirst 配置:
class ContestConfiguration : EntityTypeConfiguration<Contest>
{
ContestConfiguration()
{
// setup many-to-many table between game schedules and contests
this.HasMany(contest => contest.GameSchedules)
.WithMany(schedule => schedule.Contests)
.Map(
contestSchedule =>
{
contestSchedule.MapLeftKey("ContestId");
contestSchedule.MapRightKey("ScheduleId");
contestSchedule.ToTable("ContestSchedule", "something");
});
}
}
在使用现有时间表创建比赛时,我执行以下操作,我看到输入了两条 sql 语句,一条用于创建比赛,一条用于为 MTM 表创建记录。
Contest Add(Contest entity)
{
// setup schedules
entity.GameSchedules.ToList().ForEach(schedule => this.Context.Entry(schedule).State = EntityState.Unchanged);
// call base add method
return base.Add(entity);
}
然而,当我尝试更新时,情况就完全不同了。我尝试了很多方法,但无法让 CodeFirst 更新 MTM 表中的关系。它要么尝试删除计划以及 MTM 记录,要么什么都不做。关于如何完成这个令人兴奋的壮举有什么想法吗?
【问题讨论】:
标签: entity-framework ef-code-first many-to-many