2

このエラーの原因を突き止めようとしています。問題の解決に役立つと思われるコードの関連領域をいくつかリストしました。

レシピ エンティティのメンバー コレクションは次のとおりです。

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();
4

2 に答える 2

6

I'm not sure this is the solution but it seems like you're using different contexts in your repository.
First make sure your have the same context for each lifetime. lifetime could be different based on your project type. (e.g. for web projects, usually it is the same for each HttpContext). You can use IoC to manage your context lifetime. Good IoC libraries for .Net are autofac and Castle Windsor

Also, I think your call to InsertOrUpdate method is unnecessary (unless you're calling Find method with no tracking.) just remove the line and see if it works:

var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.Save();

One easy way to share your DbContext per HttpRequest is mentioned here.

于 2012-09-05T20:29:42.097 に答える