我有以下场景,如何在不收到System.InvalidOperationException错误的情况下执行此操作。
SomeClass.cs:
using (var eo = new MyEntities())
{
targetRole = (from p in eo.UserRoles
where p.Code == 2
select p).FirstOrDefault();
}
var user = new User
{
UserName = userName,
Password = txtPassword.Text.Trim(),
UserRole = targetRole
};
AnotherClass.AddObject(user);
AnotherClass.cs
public static void AddObject(object poco)
{
using (var eo = new MyEntities())
{
eo.AddObject("Users", poco);
eo.SaveChanges(); //<--- Exceptions Thrown.
}
}
答案 0 :(得分:5)
我自己找到了答案,我需要将targetRole对象附加到当前上下文中:
AnotherClass.cs:
public static void AddObject(object poco)
{
using (var eo = new MyEntities())
{
eo.UserRoles.Attach(targetRole); //<-- the magic
eo.AddObject("Users", poco);
eo.SaveChanges(); //<--- it works like a charm. Hoorah
}
}