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

Gio*_*lbo 14 .net c# entity-framework

我对实体框架新,所以请耐心等待......

如何将来自不同上下文的两个对象关联在一起?

以下示例引发以下异常:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Qui*_*son 11

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

编辑:想要添加这是为了提供的示例,使用asp.net将要求您充分考虑您的上下文和关系设计.

你可以简单地传递上下文.. 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;
}
Run Code Online (Sandbox Code Playgroud)