2014-04-14 28 views
0

我想在我的數據庫更新實體,但是當我嘗試這樣做,我得到一個錯誤說Violation of PRIMARY KEY constraint 'PK_Units'. Cannot insert duplicate key in object 'dbo.Units'.違反PRIMARY KEY的時候更新實體

我不是想插入一個新的數據鍵已經存在。我只是試圖從數據庫中檢索已有的項目,對其進行修改,然後進行更新。

在這裏,是執行此代碼:

// Get an already existing unit from the repository 
Unit existingUnit = pacificRepo.GetUnit(unit.c_number); 

// Update a few values of this existing unit 
existingUnit.serial_number = unit.serial_number; 
existingUnit.country = unit.country; 
existingUnit.geo_location = unit.geo_location; 

// Commit the changes to the repository 
pacificRepo.UpdateUnit(existingUnit); 

上面所用的支撐GetUnit()函數是非常簡單的:

public Unit GetUnit(string c_number) 
{ 
    return context.Units.FirstOrDefault(u => u.c_number == c_number); 
} 

這裏是有問題的功能:

public bool UpdateUnit(Unit u) 
{ 
    try 
    { 
     context.Entry(u).State = System.Data.Entity.EntityState.Modified; 
     context.SaveChanges(); 
     return true; 
    } 
    catch (Exception e) 
    { 
     return false; // Violation of PRIMARY KEY .... 
    } 

} 

編輯:這裏是單位級

public class Unit 
{ 
    [Key] 
    public string c_number { get; set; } 
    public string serial_number { get; set; } 
    public string ip_address { get; set; } 
    public string build_version { get; set; } 
    public string country { get; set; } 
    public DbGeography geo_location { get; set; } 
    public string location_at_address { get; set; } 
    public int deployment_status { get; set; } 
    public string short_description { get; set; } 
    public string notes { get; set; } 
    public int contact_id { get; set; } 
    public int reg_contact_id { get; set; } 
    public int network_id { get; set; } 

    ... 
} 

和數據庫:

CREATE TABLE [dbo].[Units] (
[c_number]   NVARCHAR (45)  NOT NULL, 
[serial_number]  NVARCHAR (45)  NULL, 
[ip_address]   NVARCHAR (45)  NOT NULL, 
[build_version]  NVARCHAR (45)  NOT NULL, 
[geo_location]  [sys].[geography] NULL, 
[location_at_address] NVARCHAR (45)  NULL, 
[deployment_status] INT    NOT NULL, 
[short_description] NVARCHAR (255) NULL, 
[notes]    TEXT    NULL, 
[contact_id]   INT    NULL, 
[reg_contact_id]  INT    NULL, 
[network_id]   INT    NULL, 
[country]    NVARCHAR (45)  NULL, 
CONSTRAINT [PK_Units] PRIMARY KEY CLUSTERED ([c_number] ASC) 
); 

有誰知道爲什麼會發生?我不想嘗試添加()它,我試圖將其狀態設置爲已修改。

+0

什麼的'Unit'類樣子的關鍵領域? –

+0

已更新我的問題以包含此問題 – gnychis

+1

一些建議:1.如果您有選項,請勿使您的主鍵NVARCHAR(45),特別是如果它實際上是名稱「c_number」所暗示的數字。2.捕獲由你的語句生成的SQL併發布它。 3.確保此表上沒有可能導致PK問題的觸發器。 –

回答

0

只是爲了咧嘴一笑,嘗試註釋掉這一行

context.Entry(u).State = System.Data.Entity.EntityState.Modified; 

你不應該設置狀態,EF應該跟蹤它。當然,這假定上下文在檢索實體和更新它之間沒有超出範圍。如果是這樣,則需要在UpdateUnit中再次檢索Units對象,然後通過將傳入對象中的值傳送到檢索到的對象來應用更改。

雖然我很好奇,但這是我在兩週內第二次看到SO上的代碼,它明確設置了對象的State。最近有沒有文章或博客文章顯示你應該這樣做?

相關問題