0

我有以下情况,如何在不出现 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);

另一个类.cs

public static void AddObject(object poco)
{
    using (var eo = new MyEntities())
    {
        eo.AddObject("Users", poco);
        eo.SaveChanges();  //<--- Exceptions Thrown.
    }
}
4

1 回答 1

5

我自己找到了答案,我需要将 targetRole 对象附加到当前上下文:

另一个类.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
   }
}
于 2012-11-17T13:16:05.837 回答