代码之家  ›  专栏  ›  技术社区  ›  Giovanni Galbo

如何使用实体框架关联来自多个上下文的对象

  •  14
  • Giovanni Galbo  · 技术社区  · 16 年前

    我是 非常

    System.InvalidOperationException:异常 两个对象之间的关系 无法定义,因为它们是 附加到不同的ObjectContext 物体。

    void MyFunction()
    {
        using (TCPSEntities model = new TCPSEntities())
        {
            EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
            er.Roles = GetDefaultRole();
            model.SaveChanges();
         }
    }
    
    private static Roles GetDefaultRole()
    {
        Roles r = null;
        using (TCPSEntities model = new TCPSEntities())
        {
            r = model.Roles.First(p => p.RoleId == 1);
        }
        return r;
    }
    

    使用一个上下文不是一个选项,因为我们在ASP.NET应用程序中使用EF。

    4 回复  |  直到 10 年前
        1
  •  11
  •   Quintin Robinson    16 年前

    您必须使用相同的上下文(可以将上下文传递给getdefaultrole方法),或者重新考虑关系并扩展实体。

    您只需传递上下文即可。。即:

    void MyFunction()
    {
        using (TCPSEntities model = new TCPSEntities())
        {
            EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
            er.Roles = GetDefaultRole(model);
            model.SaveChanges();
         }
    
    }
    
    private static Roles GetDefaultRole(TCPSEntities model)
    {
        Roles r = null;
        r = model.Roles.First(p => p.RoleId == 1);
        return r;
    }
    
        2
  •  3
  •   Ken Smith    15 年前

        public void GuestUserTest()
        {
            SlideLincEntities ctx1 = new SlideLincEntities();
            GuestUser user = GuestUser.CreateGuestUser();
            user.UserName = "Something";
            ctx1.AddToUser(user);
            ctx1.SaveChanges();
    
            SlideLincEntities ctx2 = new SlideLincEntities();
            ctx1.Detach(user);
            user.UserName = "Something Else";
            ctx2.Attach(user);
            ctx2.SaveChanges();
        }
    
        3
  •  2
  •   Eric Nelson    16 年前

    是-Entity Framework的V1不支持跨2个或更多上下文工作。

    以防你还没有找到它,在EF上有一个很好的faq http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx

        4
  •  2
  •   Ken Smith    15 年前

    http://msdn.microsoft.com/en-us/library/cc853327.aspx ),这是一个相当大的性能打击。因此,将其包装在using()结构中不是一个好主意。我在项目中所做的是通过静态方法访问它,该方法始终提供相同的上下文实例:

        private static PledgeManagerEntities pledgesEntities;
        public static PledgeManagerEntities PledgeManagerEntities
        {
            get 
            {
                if (pledgesEntities == null)
                {
                    pledgesEntities = new PledgeManagerEntities();
                }
                return pledgesEntities; 
            }
            set { pledgesEntities = value; }
        }
    

    然后我像这样检索它:

        private PledgeManagerEntities entities = Data.PledgeManagerEntities;