简体   繁体   English

在 EF Core 中更新数据的更好方法是什么

[英]What is better way to update data in EF Core

What is the best way to update data in EF core in asp.net core application?在asp.net核心应用程序中更新EF核心数据的最佳方法是什么? I can do it like this我可以这样做

public class Repository<T> : IRepository<T> where T : BaseEntity
{
    private DbContext context;
    private DbSet<T> entities;
    public Repository(DbContext context)
    {
        this.context = context;
        this.entities = context.Set<T>();
    }
    public void Update(T entity)
    {
        T exist = this.entities.Find(entity.Id);
        this.context.Entry(exist).CurrentValues.SetValues(entity);  

        this.context.SaveChanges();
    }

}

Or i can use the Update() method of DbSet.或者我可以使用 DbSet 的 Update() 方法。 But to use it I need to set QueryTrackingBehavior to "no-tracking" firstly, something like this:但是要使用它,我需要首先将 QueryTrackingBehavior 设置为“无跟踪”,如下所示:

public class Repository<T> : IRepository<T> where T : BaseEntity
{
    private DbContext context;
    private DbSet<T> entities;
    public Repository(DbContext context)
    {
        this.context = context;
        this.context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        this.entities = context.Set<T>();
    }
    public void Update(T entity)
    {
        this.entities.Update(entity); 

        this.context.SaveChanges();
    }

}

Is it a good idea?这是个好主意吗? What option is better and why?什么选择更好,为什么?

According to EF Core documentaion根据EF Core 文档

SetValues will only mark as modified the properties that have different values to those in the tracked entity. SetValues 只会将与被跟踪实体中具有不同值的属性标记为已修改。 This means that when the update is sent, only those columns that have actually changed will be updated.这意味着当更新被发送时,只有那些实际改变的列才会被更新。 ( And if nothing has changed, then no update will be sent at all. ) 如果没有任何变化,则根本不会发送更新。

So I think your first approach ( this.context.Entry(exist).CurrentValues.SetValues(entity); ) should be the best for updating entity!所以我认为你的第一种方法( this.context.Entry(exist).CurrentValues.SetValues(entity); )应该是更新实体的最佳选择!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM