c# - 当我需要更新 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 表达式?
解决方案
您不需要_dataContext.Users.Update(userFinded);
显式调用。EF 将自动检测对象中的更改并仅更新需要的字段。所以只需调用SaveChanges
DbContext 和 ChangeTracker 就会发现哪些属性发生了变化。
另一方面,EF 的 CRUD 场景并不是性能最优的。在这里,您有两个数据库往返,您必须在 transaction:FindAsync
和SaveChanges
.
不那么“可爱”但有效的是使用分离的实体:
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;
}
推荐阅读
- sql - sql查询将数据从不同的表导出到文件
- node.js - 如何设置要在所有 ejs 文件中使用的局部变量
- kotlin - 在 Reified 之后我们还需要 Class(或 KClass)吗?
- prolog - 找到一个数的所有自然除数(使用 Prolog)
- php - 120 if语句是否有任何快捷方式用于在php中使用空白文件输入类型更新数据库?
- python - 如何在redis python中将具有值的字典存储为列表
- c# - 使用asp mvc连接生物识别zkemkeeper?
- python - pandas:如何将数据框的所有数字列转换为对数
- process - 在无限超时后使用接收挂起 Erlang 进程
- ios - 如何在不阻塞用户交互的情况下执行 tableView.reloadData()