使用 dapper 执行部分数据库更新

eug*_*neK 5 c# dapper

给定数据库表用户,(姓名、姓氏、年龄和性别)。我想创建一个更新语句,而这些列中的任何一个都可以为空 - 未编辑/来自某种客户端。客户端创建一个对象 User { Name, FamilyName, Age, Sex },它将只填充更改的属性,所以基本上我正在寻找一种方法来猜测如何构建查询以及如何将数据发送给它。

除了获取整行并将其数据与我从客户端收到的对象合并之外,我根本不知道如何处理这个问题。到目前为止,这是我所做的:选择>合并>更新。

还有其他方法吗?

Ste*_*eve -3

假设你的 User 类是这样的

public class User
{
    public int UserID { get; set; }
    public string Name {get; set;}
    public string FamilyName {get;set;}
    public int? Age { get; set; }
    public string Sex { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

(注意int字段定义为Nullable<int>允许在相应字段中插入空值)

现在,设置字段(反映 null 属性的 null 值)的代码可以简单地编写为正常更新。将空值作为参数传递所需的所有操作均由 Dapper 内部完成

// Initialize just two fields and leave the other to their defaults
// (null for both strings and nullable ints)
User u = new User();
u.UserID = 1;
u.Name = "Steve";
bool ok = UpdateUser(u);
if(ok) ......


public UpdateUser(User info)
{
    using(SqlConnection cnn = new SqlConnection(@"Data Source=(LOCAL);
                                                Initial Catalog=TestDB;
                                                Integrated Security=True;"))
    {
        cnn.Open();

        // Prepare the parameters to pass to Dapper Execute 
        var pms = new
        {
           UserID = info.UserID   
           FirstName = info.Name,
           FamilyName = info.FamilyName,  // <- this is null
           Age = info.Age,                // <- this is null
           Sex = info.Sex                 // <- this is null
        };

        int rows = cnn.Execute(@"UPDATE [UserTable] 
                                 SET FirstName= @FirstName,
                                     LastName = @LastName, 
                                     Age = @Age, 
                                     Sex = @Sex
                                 WHERE UserID = @UserID",
                                 pms);
         return rows != 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 所以最终将 Age 和 Sex 字段设置为 null。我认为这与OP想要的相反。我相信他想保留这些字段的当前值并只更新那些修改过的字段。 (6认同)