如何与使用实体框架多个上下文对象 [英] How to relate objects from multiple contexts using the Entity Framework

查看:132
本文介绍了如何与使用实体框架多个上下文对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的非常新到实体框架,所以请多多包涵......

如何能与两个对象来自不同的背景在一起吗?

下面的例子抛出以下异常:

  

System.InvalidOperationException:该   两个对象之间的关系   不能被限定,因为它们是   连接到不同的ObjectContext   对象。

 无效的MyFunction()
{
    使用(TCPSEntities模式=新TCPSEntities())
    {
        EmployeeRoles ER = model.EmployeeRoles.First(P => p.EmployeeId == 123);
        er.Roles = GetDefaultRole();
        model.SaveChanges();
     }
}

私有静态角色GetDefaultRole()
{
    角色R = NULL;
    使用(TCPSEntities模式=新TCPSEntities())
    {
        R = model.Roles.First(p值=> p.RoleId == 1);
    }
    返回ř;
}
 

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

解决方案

您必须使用相同的上下文(您可以通过上下文的getdefaultrole法)或重新思考的关系和扩展的实体。

编辑:想补充这是所提供的例子中,使用asp.net会要求你完全想象出你的背景和关系的设计

您可以简单地通过上下文..即:

 无效的MyFunction()
{
    使用(TCPSEntities模式=新TCPSEntities())
    {
        EmployeeRoles ER = model.EmployeeRoles.First(P => p.EmployeeId == 123);
        er.Roles = GetDefaultRole(模型);
        model.SaveChanges();
     }

}

私有静态角色GetDefaultRole(TCPSEntities模型)
{
    角色R = NULL;
    R = model.Roles.First(p值=> p.RoleId == 1);
    返回ř;
}
 

I am very new to the entity framework, so please bear with me...

How can I relate two objects from different contexts together?

The example below throws the following exception:

System.InvalidOperationException: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

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

Using one context is not an option because we are using the EF in an ASP.NET application.

解决方案

You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity.

EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs.

You could simply pass the context.. IE:

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

这篇关于如何与使用实体框架多个上下文对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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