Ado.net command.Paramaters.AddWithValue for update statement



model

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

添加值扩展

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

但是上面的代码通过空值更新所有字段(用户显示名称除外)。如果字段的值为空,我不想更新字段。我希望我能解释一下。

谢谢...

试试这个命令

UPDATE Users SET UserName=ISNULL(@UserName, UserName), DisplayName=ISNULL(@DisplayName, DisplayName), Email=ISNULL(@Email, Email), Password=ISNULL(@Password, Password)

ISNULL(@UserName, UserName)返回参数的值(如果未NULL),如果参数NULL,则返回数据库中的值。

最新更新