1

模型

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 除外)。如果字段的值为空,我不想更新字段。我希望我能解释一下。

提前谢谢...

4

1 回答 1

3

试试这个命令

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

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

于 2013-09-19T07:09:00.093 回答