简体   繁体   English

当我需要更新 LinQ C#.Net Framework 中的记录时,如何验证所有字段?

[英]How can I validate all fields when I need to update a record in LinQ C# .Net Framework?

I'm working with C# .NET Framework and I need to know how can I validate all fields that I need to update, for example, I have a table with four fields, so, if the user only have to change a field, how can I update only that field, actually I have this code:我正在使用 C# .NET 框架,我需要知道如何验证我需要更新的所有字段,例如,我有一个包含四个字段的表,所以,如果用户只需要更改一个字段,如何我只更新那个字段,实际上我有这个代码:

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;
    }

I´m using IF sentence to validate and update the new value, but I think that is not a good practice.我正在使用 IF 语句来验证和更新新值,但我认为这不是一个好习惯。 Maybe is a lambda expression?也许是 lambda 表达式?

You do not need to call _dataContext.Users.Update(userFinded);您不需要调用_dataContext.Users.Update(userFinded); explicitly.明确地。 EF will detect changes in your object automatically and update only needed fields. EF 将自动检测 object 中的更改并仅更新所需的字段。 So just call SaveChanges for DbContext and ChangeTracker will find which properties are changed.所以只需为 DbContext 调用SaveChanges ,ChangeTracker 就会发现哪些属性发生了变化。

From other side, EF's CRUD scenario is not optimal for performance.另一方面,EF 的 CRUD 场景并不是性能最优的。 Here you have two database roundtrips and you have to cover them explicitly in transaction: FindAsync and SaveChanges .在这里,您有两个数据库往返,您必须在事务中明确地覆盖它们: FindAsyncSaveChanges

Not so "cute" but effective is to use detached entity:不那么“可爱”但有效的是使用分离的实体:

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;
}

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

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