How to relate objects from multiple contexts using the Entity Framework


Question

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.

1
14
3/6/2015 4:38:25 AM

Accepted Answer

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;
}
11
10/1/2008 6:34:15 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon