2014-02-10 143 views
0

的情況是:更新實體和相關實體

class Foo { 
    [Key] 
    public int Id { get; set; } 
    public List<Bar> Bars { get; set; } 
} 

class Bar { 
    [Key] 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

我必須實現一個簡單的CRUD OPS是這樣的:

public void InsertOrUpdateFoo(Foo foo) { 

    var db = new MyContext(); 

    //here some pseudocode 
    if (foo exists) { 

     d.Foos.Add(foo); 

    } else { 

     //here which is the best solution? 
     //a good tradeoff between performance and code semplicity 

     //case 1: delete first and add 
     db.Foos.Remove(oldFoo); 
     db.Add(foo); 
     db.SaveChanges(); 

     //case 2: there is some functionality that allows you to update the entity like: 
     db.Modify(oldEntity, newEntity); 

    } 

    db.Dispose(); 
} 

在更新方案,這似乎是最好的選擇?

  1. 刪除和添加
  2. 手動管理更新(的foreach子實體)
  3. 一些其他技術?

回答

0

根據http://forums.asp.net/t/1889944.aspx中的想法,您可以檢查實體的ID屬性是否爲默認值,例如int爲0。如果是這樣,它是新的,應該添加。如果不是,則更新它。

一旦實體連接到上下文,就可以通過它的EntityState向上下文指示。您可以通過該實體的DbEntityEntry通過上下文的Entry<T>()方法獲得對此的訪問權限。

創建上下文時,您還需要使用using語句,該語句將管理上下文的範圍,並在塊結束時自動調用Dispose

最好將其拆分成實際上將更改保存爲插入或更新的部分(存儲庫方法,很可能,但將在此處單獨使用以簡化)以及操作實體的代碼。

定義的方法(根據您的代碼):

public void InsertOrUpdateFoo(DbContext db, Foo foo) {   
    if (foo.ID == 0) { // assuming Foo's unique identifier is named ID 
     db.Entry(entity).State = EntityState.Added; 
    } else { 
     db.Entry(entity).State = EntityState.Modified; 
    } 
    db.SaveChanges(); 
} 

用法:

// for when you're creating new entities 
var newFoo = new Foo(); 
newFoo.Name = "A Name"; 
using(var context = new MyContext()) 
{ 
    context.Add(newFoo); 
    InsertOrUpdate(context. newFoo); 
} 

// ... 
// for when you're using existing entities 
// you have an ID from somewhere in variable "id" 
using (var context = new MyContext()) 
{ 
    var existingFoo = context.Find(id); 
    if (existingFoo != null) 
    { 
     existingFoo.Name = "ChangedTheName"; 
     InsertOrUpdate(context, existingFoo); 
    } 
}