我的非常新到实体框架,所以请多多包涵......
我如何能与两个对象来自不同的背景在一起吗?
下面的例子抛出以下异常:
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;
}
相关推荐
最新文章