EF codeFirst:两个对象之间的关系不能被限定,因为它们连接到不同的ObjectContext对象 [英] EFCodeFirst : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

查看:1206
本文介绍了EF codeFirst:两个对象之间的关系不能被限定,因为它们连接到不同的ObjectContext对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是什么原因造成这个错误,我列出了一些我的code的相关领域应该有希望帮助回答我的问题。

配方实体的成员集合如下图所示:

  public虚拟的IList<&成员GT;成员{搞定;组; }

和这里的食谱收集有关成员单位:

  public虚拟的IList<&配方GT;食谱{搞定;组; }

我为了使一个单独的表一个多一对多的关系建立我的DbContext时做以下

 保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        //必须指定使用EF流利的API,否则我结束了这些映射
        //被放置的配方和成员表内外资重点领域,这将不
        //给一个多一对多的关系
        modelBuilder.Entity<&配方GT;()
            .HasMany(R => r.Members)
            .WithMany(M => m.Recipes)
        .MAP(X => {
            x.ToTable(食谱);使用映射表的许多一对多的关系//
            x.MapLeftKey(RecipeId);
            x.MapRightKey(MEMBERID);
        });        modelBuilder.Entity<&配方GT;()
            .HasRequired(X => x.Author)
            .WithMany()
            .WillCascadeOnDelete(假);    }

我也是种子我的数据库,当模型更改和所有我不得不做的就是添加到配方的成员集合,它似乎能休息了排序为我,并把相关的按键在我的食谱关系表。

这是一些我的食谱控制器操作的code执行工作的:

  VAR memberEntity = memberRepository.Find((INT)MEMBERID);
VAR recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();

下面是我的食谱库中插入或更新方法

 公共无效InsertOrUpdate(配方配方)
    {
        如果(recipe.Id ==默认值(INT))
        {
            //新建实体
            context.Recipes.Add(配方);
        }其他
        {
            //现有实体
            context.Entry(配方).STATE = EntityState.Modified;
        }
    }

我得到的误差出现InvalidOperationException:两个对象之间的关系不能被限定,因为它们连接到不同的ObjectContext对象。在这条线:

  context.Entry(配方).STATE = EntityState.Modified;

有谁知道为什么会发生?我一定要将该成员添加到配方,反之亦然得到这个工作?我不知道是什么问题,因为recipeEntity似乎是正确的。

任何帮助将是AP preciated,谢谢。

修改
上下文被在每个存储库中创建(RecipeRepository&放大器; MemberRepository)所示,所以我presume this是在不同的上下文中的问题正在被用于每个.Find()请求?而引起的问题?

 私人EatRateShareDbContext背景=新EatRateShareDbContext();


解决方案

我不知道这是解决方案,但它似乎像你在你的仓库使用不同的语境。结果
首先请确保您为每个生命周期相同的上下文。一生可以根据您的项目类型有所不同。 (例如,用于web项目,一般的是每个的HttpContext 相同)。您可以使用IoC容器来管理上下文生存期。对于.NET好的IOC库 autofac 并的温莎城堡

另外,我觉得你打电话 InsertOrUpdate 方法是不必要的(除非你调用查找法无。跟踪)只是删除线,看看它是否工作:

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

中提到,分享您的每的DbContext 的Htt prequest 一个简单的方法的这里

I am trying to find out what is causing this error, I have listed some of the relevant areas of my code that should hopefully help answer my problem.

The recipe entity's members collection is as shown below:

public virtual IList<Member> Members { get; set; }

and here is the Recipes collection on the member entity:

public virtual IList<Recipe> Recipes { get; set; }

I do the below when creating my DbContext in order to make a many-to-many relationship in a separate table

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

    }

I also seed my database when the model changes and all I have had to do is add to a recipe's member collection and it seems to be able to sort the rest out for me and place the relevant keys in my cookbook relationship table.

This is some of the code in my recipe controller action that performs the work:

var memberEntity = memberRepository.Find((int)memberId);
var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();

Here is the insert or update method on my Recipe repository

    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;
        }
    }

I get an error of "InvalidOperationException : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." on this line:

context.Entry(recipe).State = EntityState.Modified;

Does anyone know why that would happen? Do I have to add the member to the recipe and vice versa to get this to work? I'm not sure what the problem is because the recipeEntity seems to be the correct one.

Any help would be appreciated, thanks.

EDIT The context is being created in each repository (RecipeRepository & MemberRepository) as shown, so I presume this is the problem in that a different context is being used for each .Find() request? and that causes problems?

private EatRateShareDbContext context = new EatRateShareDbContext();

解决方案

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.

这篇关于EF codeFirst:两个对象之间的关系不能被限定,因为它们连接到不同的ObjectContext对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆