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

标签 c# dapper

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

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

还有其他办法吗?

最佳答案

假设你的用户类是这样的

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

}

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

现在,设置字段的代码反射(reflect)了空属性的空值,可以简单地编写为正常更新。将空值作为参数传递所需的所有内容均由 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;
    }
}

关于c# - 使用 dapper 执行部分数据库更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038625/

相关文章:

c# - C# 中的任意大整数

c# - 简单的所见即所得文本框 ASP.NET

c# - 更改对象列表的编码

c# - Dapper QuerySingleOrDefault 不返回 null

c# - Dapper 和 Varbinary(max) 流参数

c# - 使用存储过程从 Dapper.net 查询返回值

c# - 如何处理此类问题 UnauthorizedAccessException Was handli Error?

c# - 使用 Json.NET 对 DataContractJsonSerializer 使用的结构中的字典进行(反)序列化?

c# - 这是否符合任何已知的设计模式?

小巧玲珑的错误 : Each grid can only be iterated once