EF Core 中 AddorUpdate 方法的替代方法是什么?

Nau*_*san 8 c# generics repository-pattern entity-framework-core asp.net-core

我想使用如下所示的 EF Core 在通用存储库中实现 ADDorUpdate() 方法?谁能帮我?

  public virtual void AddOrUpdate(T entity)
    {
        #region Argument Validation

        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }
        #endregion
         DbSet.AddOrUpdate(e => e.Id, entity);  
        this.DbContext.SaveChanges();
    }
Run Code Online (Sandbox Code Playgroud)

Arm*_*our 17

只需使用

context.Update(entity);
Run Code Online (Sandbox Code Playgroud)

它完全AddOrUpdate基于实体 PrimaryKey 的值(0 表示添加,> 0 表示更新):

public virtual void AddOrUpdate(T entity)
{
    if (entity == null)
        throw new ArgumentNullException("entity");

     this.DbContext.Update(entity);  
     this.DbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:这仅适用于 AUTOGENERATED 键,否则您将得到 ConcurrencyException (3认同)
  • 当您不跟踪实体并且存在重复密钥冲突时该怎么办?一种高效的原始 SQL/MySQL 查询方法是在查询违反约束时“ON DUPLICATE KEY UPDATE”,然后更新查询。否则,您需要使用重复查询来查询一行以查看它是否存在,然后决定在代码中添加或更新它,这样效率较低,并且无法很好地扩展,而另一种方式直接使用您为其提供数据的数据库引擎,它决定如何通过一个查询来处理它,并且减少性能损失。在你的代码中你可能还不知道它是否是重复的...... (2认同)