首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新实体和相关实体

更新实体和相关实体
EN

Stack Overflow用户
提问于 2014-02-10 10:23:14
回答 1查看 70关注 0票数 0

设想如下:

代码语言:javascript
复制
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操作:

代码语言:javascript
复制
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. 其他一些技巧??
EN

回答 1

Stack Overflow用户

发布于 2014-03-05 03:20:01

根据http://forums.asp.net/t/1889944.aspx中的思想,您可以检查实体的ID属性是否是默认值,例如int的值为0。如果是这样的话,它是新的,应该添加。如果没有,那么更新它。

一旦实体附加到上下文,它的EntityState就可以将其指示给上下文。您可以通过实体的DbEntityEntry,通过上下文的Entry<T>()方法获得对此的访问。

您还需要在创建上下文时使用using语句,该语句将管理上下文的作用域,并在块结束时自动对其调用Dispose

最好将其划分为实际将更改保存为insert或update的部分(很可能是存储库方法,但为了简单起见将在这里单独使用)和操作实体的代码。

方法的定义(基于您的代码):

代码语言:javascript
复制
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();
}

用法:

代码语言:javascript
复制
// 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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21674488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档