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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/158986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:09:19  来源:igfitidea点击:

How to relate objects from multiple contexts using the Entity Framework

提问by Giovanni Galbo

I am verynew 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.

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

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

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

采纳答案by Quintin Robinson

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.

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

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.

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

You could simply pass the context.. IE:

你可以简单地传递上下文.. 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;
}

回答by Eric Nelson

Yep - working across 2 or more contexts is not supported in V1 of Entity Framework.

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

Just in case you haven't already found it, there is a good faq on EF at http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx

以防万一您还没有找到它,在http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx上有一个很好的 EF 常见问题解答

回答by Ken Smith

From what I understand, you want to instantiate your model (via the "new XXXXEntities()" bit) as rarely as possible. According to MS (http://msdn.microsoft.com/en-us/library/cc853327.aspx), that's a pretty substantial performance hit. So wrapping it in a using() structure isn't a good idea. What I've done in my projects is to access it through a static method that always provides the same instance of the context:

据我了解,您希望尽可能少地实例化模型(通过“new XXXXEntities()”位)。根据 MS ( 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; }
    }

And then I retrieve it like so:

然后我像这样检索它:

    private PledgeManagerEntities entities = Data.PledgeManagerEntities;

回答by Ken Smith

Another approach that you could use here is to detach objects from one context, and then attach them to another context. That's a bit of a hack, and it may not work in your situation, but it might be an option.

您可以在此处使用的另一种方法是从一个上下文中分离对象,然后将它们附加到另一个上下文。这有点黑客,它可能不适用于您的情况,但它可能是一种选择。

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