2016-08-23 64 views
0

我有以下代碼:System.InvalidOperationException:屬性 '一致,如Emp_status' 是對象的密鑰信息的一部分並且不能被修改

public partial class Emp_Details 
{ 
    public long Emp_ID { get; set; } 
    public string Emp_Title { get; set; } 
    public string Emp_Name { get; set; } 
    public string Emp_LastName { get; set; } 
    public string Emp_Status{ get; set; } 
} 

實體代碼

 using (LoginEntities dbcontext = new LoginEntities()) 
      {     
      Emp_Details emp = dbcontext.Emp_Details.Single(i => i.Emp_ID == empid); 
       emp.Emp_Status = status; 
       dbcontext.SaveChanges();    
      } 

我得到的例外

System.InvalidOperationException: The property 'Emp_Status' is part of the object's key information and cannot be modified. 

我已經搜索了一個解決方案,發現2個可能的修復:

1)設置一個主鍵。如果表上沒有主鍵,它將簡單地選擇不可爲空的列作爲連接的主鍵,並且該實體將被讀取/只讀。

2)使用直接更新,如:

dbcontext.Database.ExecuteSqlCommand(
"UPDATE Emp_Details SET [Emp_Status] = {0} WHERE [Emp_ID] = {1}", status, empid); 

有沒有辦法做到這一點更新,而無需觸摸數據庫,設置主鍵,或與類文件爛攤子?

回答

2

您的實體沒有主鍵。所以:

public partial class Emp_Details { 
    public long Id { get; set; } // pay attention to this 
    public string Emp_Title { get; set; } 
    public string Emp_Name { get; set; } 
    public string Emp_LastName { get; set; } 
    public string Emp_Status{ get; set; } 
} 

或者

public partial class Emp_Details { 
    public long Emp_DetailsId { get; set; } // pay attention to this 
    public string Emp_Title { get; set; } 
    public string Emp_Name { get; set; } 
    public string Emp_LastName { get; set; } 
    public string Emp_Status{ get; set; } 
} 

或者

public partial class Emp_Details { 
    [Key] // pay attention to this 
    public long Emp_ID { get; set; } 
    public string Emp_Title { get; set; } 
    public string Emp_Name { get; set; } 
    public string Emp_LastName { get; set; } 
    public string Emp_Status{ get; set; } 
} 

的上述變化的每個,將解決這個問題。

+0

因此,這只是在OP的可能解決方案中做第一名,是嗎? – David

+0

我上面試過但是同樣的錯誤顯示 – Pravin

+0

@PhatWrat你是什麼意思?我沒有明白): –

相關問題