【问题标题】:How can I validate all fields when I need to update a record in LinQ C# .Net Framework?当我需要更新 LinQ C# .Net Framework 中的记录时,如何验证所有字段?
【发布时间】:2021-08-12 20:51:21
【问题描述】:

我正在使用 C# .NET Framework,我需要知道如何验证我需要更新的所有字段,例如,我有一个包含四个字段的表,因此,如果用户只需要更改字段,我怎样才能只更新那个字段,实际上我有这个代码:

public async Task<ServiceResponse<User>> UpdateUser(User newUserUpdate)
    {
        ServiceResponse<User> serviceResponse = new();

        //Este llamada es para buscar por medio del ID ingresado por el usuario
        User userFinded = await _dataContext.Users.FindAsync(newUserUpdate.Id);

        //¿Como iterar para validar que campos actualizar?

        if (newUserUpdate.userName != null) userFinded.userName = newUserUpdate.userName;
        if (newUserUpdate.email != null) userFinded.email = newUserUpdate.email;
        if (newUserUpdate.password != null) userFinded.password = newUserUpdate.password;

        _dataContext.Users.Update(userFinded);
        _dataContext.SaveChanges(); 
        serviceResponse.Message = "Usuario Actualizado Exitosamente";

        return serviceResponse;
    }

我正在使用 IF 语句来验证和更新新值,但我认为这不是一个好习惯。也许是 lambda 表达式?

【问题讨论】:

  • 删除_dataContext.Users.Update(userFinded);,它将按预期工作。
  • @SvyatoslavDanyliv 如果 OP 删除了_dataContext.Users.Update(userFinded);,那么将不会保存任何更改。
  • @NicholasHunter 为什么? OP 从上下文中获取实体。做出改变。并致电Save
  • @NicholasHunter,你必须重新学习 EF。无需调用Update 来更新数据库中的实体。 Change Tracker 将检测到对象的新值与FindAsync 调用后不同,并仅自动更新需要的字段。

标签: c# asp.net visual-studio linq .net-framework-4.8


【解决方案1】:

您无需显式调用_dataContext.Users.Update(userFinded);。 EF 将自动检测对象中的更改并仅更新需要的字段。因此,只需为 DbContext 调用 SaveChanges,ChangeTracker 就会发现哪些属性发生了更改。

从另一方面来看,EF 的 CRUD 场景并不是性能最优的。这里有两个数据库往返,你必须在事务中明确地覆盖它们:FindAsyncSaveChanges

不那么“可爱”但有效的是使用分离的实体:

public async Task<ServiceResponse<User>> UpdateUser(User newUserUpdate)
{
    ServiceResponse<User> serviceResponse = new();

    if (newUserUpdate.userName != null) ||
        newUserUpdate.email    != null) ||
        newUserUpdate.password != null)
    {
        _dataContext.Users.Attach(newUserUpdate);
        var entry = _dataContext.Entry(newUserUpdate);

        if (newUserUpdate.userName != null) entry.Property(x => x.userName).IsModified = true;
        if (newUserUpdate.email    != null) entry.Property(x => x.email).IsModified = true;
        if (newUserUpdate.password != null) entry.Property(x => x.password).IsModified = true;

        await _dataContext.SaveChangesAync();
    }

    serviceResponse.Message = "Usuario Actualizado Exitosamente";

    return serviceResponse;
}

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多