2013-08-30 37 views
0

我正在使用EntityFramework將項目版本號保存到數據庫 。在UI頁面中,用戶鍵入版本(主要,次要,構建)整數值並單擊保存按鈕 在I保存,我想確保在數據庫中沒有創建重複版本。實體框架如何防止重複項進入db

什麼,我想是確保major.minor.build組合是唯一

ProjVersion newVersion=new ProjVersion(); 
newVersion.Major=10; 
newVersion.Minor=1; 
newVersion.Build=1; 
this.repository.Add<ProjVersion>(newVersion); 
//here how can I ensure that no duplicate versions are added to database 
this.repository.SaveChanges(); 

[Serializable] 
    public class ProjVersion 
    { 
     [Key] 
     public int Version_Id { get; set; } 
     public int Major { get; set; } 
     public int Minor { get; set; } 
     public int Build { get; set; } 
    } 

回答

0

檢查是否有數據庫具有相同的細節,你想添加什麼樣的任何條目。如果沒有,那麼這是一個新版本,你應該添加它,如果是的話,那麼它是一個重複的,你應該做任何你想要處理的情況。

if (repository.Get(x => x.Major == newVersion.Major && 
    x.Minor == newVersion.Minor && x.Build == newVersion.Build) 
    .Count() > 0) 
{ 
    //notify the user that they are making a duplicate entry 
} 
else 
{ 
    repository.SaveChanges(); 
} 
+1

並在其周圍添加「使用(TransactionScope tsTransScope = new TransactionScope())」。 – Ubikuity

+0

version_id是一個自動生成的數字。因此每次添加新記錄時,它都會生成一個新的數字作爲version_id。但這裏我正在嘗試確保major.minor.build組合是唯一的 – Millar

+0

@Millar,是啊,這是我的錯誤。它已被編輯,現在顯示正確的代碼。 –

0

這聽起來像你需要使用Compound Key,所有的屬性(列)主鍵的一部分。

{ 
    [Key, Column(Order = 0)] 
    public int Major { get; set; } 

    [Key, Column(Order = 1)] 
    public int Minor { get; set; } 

    [Key, Column(Order = 2)] 
    public int Build { get; set; } 
} 

嘗試使用匹配鍵插入記錄將產生一個Exception

+0

雖然這樣可以達到不允許重複條目的預期結果,但它也會帶來複合主鍵的複雜性,例如不允許修改任何這些字段。 –

+0

如果這是用於版本規劃的話,我可以看到在更改'Version'時的用法,但是如果它代表內置版本(我認爲這是因爲它包含'Build'屬性),那麼爲什麼要更改版本呢?這將是一個不同的版本 - 不是嗎? – STW

+0

如果沒有完整的項目規範,我們無法確定,但人們會犯錯誤。如果他們意外地將10.1.1版本輸入爲10.1.2,那麼將無法更改刪除該行的那一短。如果這個項目不允許刪除呢?那麼它必須保持在那裏,當它們真正到達版本10.1.2時會發生什麼? –