【问题标题】:C# remove SQL from method and use stored procedure & DapperC# 从方法中删除 SQL 并使用存储过程和 Dapper
【发布时间】:2016-10-22 02:12:52
【问题描述】:

我正在尝试将一种方法转换为使用 Dapper 的存储过程。但我对var result =... 发生的事情感到很困惑

public Task<TUser> FindByIdAsync(Guid userId)
{
    var sql = @"SELECT *
                FROM IdentityUser
                WHERE UserId = @USERID";

    using (var connection = new SqlConnection(_connection))
    {
        var result = connection.Query<TUser, IdentityProfile, TUser>(sql, (user, profile) => { user.Profile = profile;
                             return user; }, 
                          new { userId }, splitOn: "UserId").SingleOrDefault();

        return Task.FromResult(result);
     }
}

这是我所拥有的:

public Task<TUser> FindByIdAsync(Guid userId)
{
    using (var connection = new SqlConnection(_connection))
    {
        var param = new DynamicParameters();
        param.Add("@UserId", userId);

        return Task.FromResult(connection.Query("IdentityGetUserById", param, commandType: CommandType.StoredProcedure).SingleOrDefault());
    }
}

【问题讨论】:

  • 您有问题吗?这是什么?

标签: c# asp.net sql-server stored-procedures dapper


【解决方案1】:

但我对 var result =... 的情况感到很困惑。

不要混淆,这是简单的 Dapper 功能

让我解释一下以下代码的作用:

var result = connection.Query<TUser, IdentityProfile, TUser>
                        (sql, (user, profile) => 
                        { 
                             user.Profile = profile;
                             return user; 
                        }, new { userId }, 
                       splitOn: "UserId").SingleOrDefault();
  1. User 是一个复杂类型,其中包含 Profile 类型的一部分
  2. 执行Sql查询的结果是一个组合的表格数据(用户和Profile都有列),在UserId列自动拆分,然后代表Profile类型,填写用户类型,按照逻辑user.Profile = profile
  3. 由于查询结果为IEnumerable&lt;TUser&gt;,因此调用SingleOrDefault,如果返回Single record则返回数据或返回null
  4. 这是自动绑定complex types的标准机制

现在,当您运行存储过程时,预计会出现相同类型的代码,IdentityGetUserById,唯一的更改是用存储过程名称替换真正的 Sql(完成),告诉 Dapper 您正在执行存储过程(完成),您已经使用DynamicParameter绑定参数,也可以是匿名类型。结果将采用类似的格式,您可以进行完全相同的绑定,检查以下代码,只需少量修改:

using (var connection = new SqlConnection(_connection))
{
        var result = connection.Query<TUser, IdentityProfile, TUser>
        ("IdentityGetUserById", 
         commandType: CommandType.StoredProcedure,
         (user, profile) => 
                        { 
                           user.Profile = profile;
                           return user; 
                        }, new { userId }, 
                       splitOn: "UserId").SingleOrDefault();

          return Task.FromResult(result);
         );
}

其实我已经把Dynamic Parameters去掉了,用Anonymous type保证和Sql代码一致

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2011-09-08
    • 2017-08-24
    相关资源
    最近更新 更多