このエラーの原因を突き止めようとしています。問題の解決に役立つと思われるコードの関連領域をいくつかリストしました。
レシピ エンティティのメンバー コレクションは次のとおりです。
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);
}
また、モデルが変更されたときにデータベースをシードし、レシピのメンバーコレクションに追加するだけで、残りを整理して、関連するキーをクックブックの関係テーブルに配置できるようです。
これは、作業を実行する私のレシピ コントローラー アクションのコードの一部です。
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 : The relationship between the two objects cannot be attached because they are attached to different ObjectContext objects.」というエラーが表示されます。この行で:
context.Entry(recipe).State = EntityState.Modified;
なぜそれが起こるのか誰か知っていますか?これを機能させるには、メンバーをレシピに追加する必要がありますか? レシピエンティティが正しいように見えるため、何が問題なのかわかりません。
どんな助けでも感謝します、ありがとう。
EDITコンテキストは、示されているように各リポジトリ(RecipeRepositoryとMemberRepository)で作成されているため、.Find()リクエストごとに異なるコンテキストが使用されているという問題があると思いますか? そしてそれは問題を引き起こしますか?
private EatRateShareDbContext context = new EatRateShareDbContext();