我正在尝试找出导致此错误的原因,我列出了代码的一些相关区域,希望能够帮助解决我的问题。
菜谱实体的成员集合如下所示:
public virtual IList<Member> Members { get; set; }
这是成员实体上的 Recipes 集合:
public virtual IList<Recipe> Recipes { get; set; }
我在创建 DbContext 时执行以下操作,以便在单独的表中建立多对多关系
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// have to specify these mappings using the EF Fluent API otherwise I end up with
// the foreign key fields being placed inside the Recipe and Member tables, which wouldn't
// give a many-to-many relationship
modelBuilder.Entity<Recipe>()
.HasMany(r => r.Members)
.WithMany(m => m.Recipes)
.Map(x => {
x.ToTable("Cookbooks"); // using a mapping table for a many-to-many relationship
x.MapLeftKey("RecipeId");
x.MapRightKey("MemberId");
});
modelBuilder.Entity<Recipe>()
.HasRequired(x => x.Author)
.WithMany()
.WillCascadeOnDelete(false);
}
当模型发生变化时,我还会为我的数据库添加种子,我所要做的就是添加到菜谱的成员集合中,它似乎能够为我整理其余内容,并将相关键放入我的菜谱关系表中。
这是我的配方 Controller 操作中执行工作的一些代码:
var memberEntity = memberRepository.Find((int)memberId);
var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();
这是我的食谱存储库上的插入或更新方法
public void InsertOrUpdate(Recipe recipe)
{
if (recipe.Id == default(int))
{
// New entity
context.Recipes.Add(recipe);
} else
{
// Existing entity
context.Entry(recipe).State = EntityState.Modified;
}
}
我收到错误“InvalidOperationException:无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象。”在这一行:
context.Entry(recipe).State = EntityState.Modified;
有谁知道为什么会发生这种情况吗?我是否必须将成员添加到配方中,反之亦然才能使其正常工作?我不确定问题是什么,因为 RecipeEntity 似乎是正确的。
如有任何帮助,我们将不胜感激,谢谢。
编辑 如图所示,在每个存储库(RecipeRepository 和 MemberRepository)中创建上下文,所以我认为这是问题,因为每个 .Find() 请求使用不同的上下文?这会导致问题吗?
private EatRateShareDbContext context = new EatRateShareDbContext();
最佳答案
我不确定这是否是解决方案,但似乎您在存储库中使用了不同的上下文。
首先确保你的每一生都有相同的背景。根据您的项目类型,生命周期可能会有所不同。 (例如,对于网络项目,通常每个 HttpContext 都是相同的)。您可以使用 IoC 来管理上下文生命周期。 .Net 的良好 IoC 库是 autofac和 Castle Windsor
另外,我认为您对 InsertOrUpdate
方法的调用是不必要的(除非您在没有跟踪的情况下调用 Find
方法。)只需删除该行并查看它是否有效:
var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.Save();
提到了一种根据 HttpRequest
共享 DbContext 的简单方法 here .
关于c# - EFCodeFirst : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12289180/