簡體   English   中英

更新實體和相關實體

[英]update entity and related entities

情況是:

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; }
}

我必須實現一個像這樣的簡單操作:

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. 其他一些技巧?

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

實體附加到上下文后,可以通過其EntityState指示上下文。 您可以通過上下文的Entry<T>()方法,通過實體的DbEntityEntry獲得對此的訪問。

您還需要在創建上下文時使用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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM