在 EF Core 中更新数据的更好方法是什么
What is better way to update data in EF Core
在 asp.net 核心应用程序中更新 EF 核心数据的最佳方法是什么?
我可以这样做
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();
}
}
或者我可以使用 DbSet 的 Update() 方法。但是要使用它,我需要首先将 QueryTrackingBehavior 设置为 "no-tracking",如下所示:
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();
}
}
这是个好主意吗?哪种选择更好,为什么?
SetValues will only mark as modified the properties that have different values to those in the tracked entity. 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.)
所以我认为你的第一种方法 (this.context.Entry(exist).CurrentValues.SetValues(entity);
)
应该是更新实体的最佳选择!
在 asp.net 核心应用程序中更新 EF 核心数据的最佳方法是什么? 我可以这样做
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();
}
}
或者我可以使用 DbSet 的 Update() 方法。但是要使用它,我需要首先将 QueryTrackingBehavior 设置为 "no-tracking",如下所示:
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();
}
}
这是个好主意吗?哪种选择更好,为什么?
SetValues will only mark as modified the properties that have different values to those in the tracked entity. 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.)
所以我认为你的第一种方法 (this.context.Entry(exist).CurrentValues.SetValues(entity);
)
应该是更新实体的最佳选择!