2014-10-27 112 views
0

我有一個MVC應用程序與控制器的POST方法中的以下代碼。我正在做一個EF添加,顯然這是不對的。我想要它添加記錄,如果它不存在,否則更新。我該怎麼做?添加或更新記錄?

try 
{ 
    AttributeEntities db = new AttributeEntities(); 
    IEnumerable<string> items = viewModel.SelectedAttributes2; 
    int i = 0; 
    foreach (var item in items) 
    { 
     var temp = item; 

     // Save it 
     SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute(); 
     attribute.CustomLabel = viewModel.ItemCaptionText; 
     attribute.IsVisible = viewModel.Isselected; 
     string harmonyAttributeID = item.Substring(1, 1); 
     // attribute.OrderNumber = Convert.ToInt32(order); 
     attribute.OrderNumber = i++; 
     attribute.HarmonyAttribute_ID = Convert.ToInt32(harmonyAttributeID); 

     db.SelectedHarmonyAttributes.Add(attribute); 
     db.SaveChanges(); 
    } 
} 
+0

您需要存儲您要保存的屬性的ID,檢查它是否存在於數據庫中。如果有,請更新其屬性並保存更改。如果沒有,則創建並添加它。 – DLeh 2014-10-27 15:36:57

+0

查看關於此帖的答案。 [點擊這裏] [1] [1]:http://stackoverflow.com/questions/6966207/entityframework-insert-if-not-exist-otherwise-update – 4nis 2014-10-27 16:09:04

回答

-1

你可以導入System.Data.Entity.Migrations命名空間和使用AddOrUpdate擴展方法:

db.SelectedHarmonyAttributes.AddOrUpdate(attribute); 
db.SaveChanges(); 

編輯: 我假設SelectedHarmonyAttributes是DbSet的類型

EDIT2: 只有缺點(這可能不是你的問題),是你的實體不負責它自己的狀態改變。這意味着您可以將實體的任何屬性更新爲無效的內容,您可能希望在實體本身內部驗證它,或者可能在更新時進行其他一些處理。如果這些事情是你所關心的,你應該在實體上添加一個公共的Update方法,並首先檢查它在數據庫中的存在。例如:

var attribute = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == harmonyAttributeID); 

if (attribute != null) 
{ 
    attribute.Update(viewModel.ItemCaptionText, viewModel.Isselected, i++); 
} 
else 
{ 
    attribute = new Attribute(viewModel.ItemCaptionText, viewModel.Isselected); 
    db.SelectedHarmonyAttributes.Add(attribute); 
} 

db.SaveChanges(); 

您的更新方法可能看起來像:

public void Update(string customLabel, bool isVisible, int orderNumber) 
{ 
    if (!MyValidationMethod()) 
    { 
     throw new MyCustomException(); 
    } 

    CustomLabel = customLabel; 
    IsVisible = isVisible; 
    OrderNumber = orderNumber; 

    PerformMyAdditionalProcessingThatIAlwaysWantToHappen(); 
} 

然後讓所有的實體的屬性的公共‘搞定’,但保護的‘設置’,所以他們不能從外部進行更新實體本身。這可能會有點相切,但使用AddOrUpdate方法會假設您不想控制更新發生的方式並保護您的域實體免於進入無效狀態等。希望這有助於!

+0

小心點。這不是它的目的.... http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/ – Colin 2014-10-27 16:45:28

+0

是的,我意識到後,我發佈了答案它確實有它的缺點。我已經編輯了我的答案,以便進一步對其進行限定,但如果瞭解缺點並且比較主要關鍵字是已知的,則可能適合。 (在這個例子中,它看起來像HarmonyAttribute_ID是主鍵) – PrisonerSix 2014-10-27 17:15:36

1

您需要檢查數據庫中的記錄,試圖添加/更新。如果查找返回null,則表示它不存在於數據庫中。如果是這樣,您可以修改查找到的記錄並調用db.SaveChanges()來保存對數據庫所做的更改。

編輯:

int id = Convert.ToInt32(harmonyAttributeID); 
var existingEntry = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == id); 
+0

能否請你告訴我的代碼?如何做查找? – user2471435 2014-10-27 15:38:08

0

確定添加或更新的一種常見方法是隻需查看標識符字段並設置適當的狀態。

using System.Data; 

SelectedHarmonyAttribute attribute; 

using (var db = new YourDbContext()) 
{ 
    db.Entry(attribute).State = attribute.HarmonyAttribute_ID == 0 ? EntityState.Added : EntityState.Modified; 

    db.SaveChanges(); 
}