只有当属性的当前值为null时,才能设置EntityKey属性

时间:2012-11-17 12:52:45

标签: c# .net linq entity-framework

我有以下场景,如何在不收到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.
    }
}

1 个答案:

答案 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
   }
}