模型
public class Users
{
public int Id { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public DateTime? LastLoginDate { get; set; }
public string LastLoginIP { get; set; }
}
我只想像这样在数据库中更新用户显示名称
repository.Update(new User{ DisplayName = "display name" });
如何创建 sql 查询?我应该动态创建查询吗?还是另一种方式?
我使用以下代码来更新用户。
public int Update(Users user)
{
SqlCommand command = GetCommand("UPDATE Users SET UserName=@UserName, DisplayName=@DisplayName, Email=@Email, Password=@Password");
command.Parameters.AddWithValue("@UserName", user.UserName, null);
command.Parameters.AddWithValue("@DisplayName", user.DisplayName, null);
command.Parameters.AddWithValue("@Email", user.Email, null);
command.Parameters.AddWithValue("@LastLoginDate", user.LastLoginDate, null);
command.Parameters.AddWithValue("@LastLoginIP", user.LastLoginIP, null);
command.Parameters.AddWithValue("@Password", user.Password, null);
return SafeExecuteNonQuery(command);
}
AddWithValueExtension
public static SqlParameter AddWithValue(this SqlParameterCollection target, string parameterName, object value, object nullValue)
{
if (value == null)
{
return target.AddWithValue(parameterName, nullValue ?? DBNull.Value);
}
return target.AddWithValue(parameterName, value);
}
但上面的代码通过空值更新所有字段(用户 displayName 除外)。如果字段的值为空,我不想更新字段。我希望我能解释一下。
提前谢谢...