How to use the Entity Framework to connect items from different contexts.

.net c# entity-framework

Question

Please be patient; I'm very new to the entity framework.

How can I connect two items from distinct contexts?

The following exception is thrown by the following example:

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

We are utilizing the EF in an ASP.NET application, thus having a single context is not an option.

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

Accepted Answer

You will either need to continue using the same context (you can do this by passing the context to the getdefaultrole function) or you may expand the entity and reconsider the relationships.

EDIT: I wanted to clarify that utilizing Asp.net requires you to carefully consider your context and relationship designs. This was for the example supplied.

You could just transmit 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

Popular Answer

You might also use the method of removing things from one context and reattaching them to another. That is a little bit of a hack, and it may not work for you, but it is an alternative.

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


Related Questions





Related

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