2012-11-17 91 views
0

我有以下情況,如何在不獲取System.InvalidOperationException錯誤的情況下執行此操作。只有在屬性的當前值爲空時才能設置EntityKey屬性

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

好嗎? e是拋出的錯誤,是什麼行? – Arran

+0

On eo.SaveChanges(); – NET3

+0

'User'是你自己的類型還是EF生成的? – Alex

回答

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 
    } 
} 
+0

將其標記爲答案。 – Alex

相關問題