首页 > 解决方案 > 当我需要更新 LinQ C# .Net Framework 中的记录时,如何验证所有字段?

问题描述

我正在使用 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 表达式?

标签: c#asp.netvisual-studiolinq.net-framework-4.8

解决方案


您不需要_dataContext.Users.Update(userFinded);显式调用。EF 将自动检测对象中的更改并仅更新需要的字段。所以只需调用SaveChangesDbContext 和 ChangeTracker 就会发现哪些属性发生了变化。

另一方面,EF 的 CRUD 场景并不是性能最优的。在这里,您有两个数据库往返,您必须在 transaction: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;
}

推荐阅读