【问题标题】:Dapper's parameterized Update and Insert?Dapper 的参数化更新和插入?
【发布时间】:2016-10-26 06:38:13
【问题描述】:

我将 Dapper 用于我的 Windows C# 表单应用程序。我注意到他们的大多数 CRUD 操作都以类名作为参数。 例如如下两个表:

    "Employee" Table
        Column Name  | Data Type |
        -------------------------
        EmpName      | string    |
        EmpNo        | string    |
        --------------------------

Employee.cs
[Table("Employee")]
public class Employee
{
   [Key]
   public string EmpNo {get;set;}
   public string EmpName {get;set;}
}

    "User" Table
        Column Name   | Data Type |
        -------------------------
        UserName      | string    |
        UserNo        | string    |
        --------------------------
User.cs
[Table("User")]
public class User
{
   [Key]
   public string UserNo {get;set;}
   public string UserName {get;set;}
}


    eg. var users= connection.Query<User>("select * from User" );
        var employees = connnection.GetList<Employee>();

将执行适当的任务。 但是,据我所知,connection.Insert&lt;User&gt;(user); or connection.Update&lt;Employee&gt;(emp); 不存在。 如果我错了,请纠正我,是否有任何解决方法可以让更新和插入让 dapper 知道类类型? 我很清楚Query()Execute(),事实上我现在正在使用它们。有没有可能让它像GetList(ClassName); 一样简单?

【问题讨论】:

  • 是的,我知道 Query 和 Execute 函数,我正在寻找的是让 Insert 和 Update 像 GetList(ClassName) 和 Get(class) 一样简单。
  • @RahulMakwana 您需要编写自己的包装器才能做到这一点。据我了解,编写 Dapper 的人按照我在下面回答的方式进行操作,以使事情保持开放。很多时候,代码只需要更新特定的列,所以传递一个对象会假设你想要更新所有的列,这是更新的一个很大的假设。就目前而言,它是相当精确的代码。
  • ?@BenHoffman 我明白这一点,如果我每次更新时都可以更新所有列怎么办。我想你是对的,我需要编写自己的辅助扩展来做到这一点。
  • 你看过 dapper.contrib 吗?它添加了一些 CRUD 功能...

标签: c# sql dapper


【解决方案1】:

Dapper 处理事情的方式与您所要求的有所不同。没有插入或更新方法。相反,您将希望对 Insert 这样做:

var p = new Product { Name = "Sam", Description = "Developer" };
p.Id = cnn.Query<int>(@"insert Products(Name,Description) 
values (@Name,@Description) 
select cast(scope_identity() as int)", p).First();

这直接来自 Sam Saffron,https://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper

对于更新,您需要这样的代码:

public bool Update(Employee employee)
{
    string query = "UPDATE EMPLOYEE SET NAME = @Name WHERE Id = @Id";
    var count = this.db.Execute(query, employee);
    return count > 0;
}

【讨论】:

  • 如果您不需要找回身份,也可以使用Execute
  • 注:dapper.contrib 增加了很多 CRUD 支持
【解决方案2】:

感谢 Marc Gravell。我找到了here。 Dapper 的开源开发确实有 Insert&lt;ClassName&gt;(obj)Update&lt;ClassName&gt;(obj) 的实现。

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多