【问题标题】:Parameters not working with Dapper.Net参数不适用于 Dapper.Net
【发布时间】:2013-07-29 04:49:51
【问题描述】:

我已经从 here 链接下载了 SqlMapper.cs 文件。

虽然我遇到了一些令人困惑的麻烦。每当我使用参数时,我的查询都会返回空集合,即使我很确定我使用的是相同的字符串数据。

这是一段用于提取数据的sn-p代码。

using (PhoenixConnection connection = new PhoenixConnection(Open: true))
{
    //this example works, returns 1 token object
    string queryWorks = @"Select AccountName, AccountToken from btsource.accounts
    where AccountName = 'RekindledPhoenix'";

    // replaces 'RekindledPhoenix' with a parameter, returns empty collection
    string queryDoesnt = @"Select AccountName, AccountToken from btsource.accounts 
    where AccountName = @AccountName";

    var tokenList = connection.Query<TokenRequest>(queryWorks);
    var tokenList = connection.Query<TokenRequest>(queryDoesnt, new { AccountName = "RekindledPhoenix" });
    return tokenList.FirstOrDefault();
}

这是我正在使用的课程...

public class TokenRequest
{
    public string AccountName { get; set; } //`AccountName` VARCHAR(50) NOT NULL
    public long AccountToken { get; set; } //`AccountToken` BIGINT(20) NOT NULL
}

这是我的 PhoenixConnection 对象中的包装函数。

public IEnumerable<T> Query<T>(string Query, dynamic Parameters = null)
{
    return _connection.Query<T>(Query, (object)Parameters);
}

我试过了:

  • 仔细检查 mysql 表名和值
  • 更改包装器以使用除动态之外的任何内容(无效)
  • 验证连接是否打开
  • 原始 mysqlConnection 对象、命令文本等

我可能缺少什么

参数有什么特殊设置吗?

编辑:

使用原始MySqlConnection 参数更适合? 而不是@,但仍然不适用于Dapper。

我注意到 Dapper 中有特定的行使用正则表达式 ([@:]) 语句提取参数,尽管问号似乎被忽略了。我应该改变什么来获得预期的结果?

【问题讨论】:

  • 什么是 PhoenixConnection?这不是我熟悉的。如果您使用原始 ADO.NET(CreateCommand、Parameters.Add 等)编写此代码 - 可以吗?
  • @MarcGravell 是的,PhoenixConnection 是一个小型包装器,用于处理连接状态、处置等。参数与 MySqlConnection 类一起使用,但仅在使用 问号 时。
  • 这真的取决于您使用的 MySql 连接器版本。有些(例如 5.2.7)确实可以使用“@”,而有些则不能。

标签: c# mysql .net dapper


【解决方案1】:

我发现了问题。在使用原始MySqlConnection 对象执行我的查询后,它引导我搜索为什么@ 符号在我的任何语句中都不起作用。过去我一直使用?,所以这种行为对我来说很奇怪。

更改 SqlMapper.cs

将以下@ 符号更改为? (带有近似行号)

第 1863 行:if (identity.sql.IndexOf("?" + prop.Name, StringComparison.InvariantCultureIgnoreCase) &lt; 0

第 1831 行:return parameters.Where(p =&gt; Regex.IsMatch(sql, "[?:]" + p.Name + "([^a-zA-Z0-9_]+|$)", RegexOptions.IgnoreCase | RegexOptions.Multiline));

解决了我的问题!

【讨论】:

  • 好吧,这让我很尴尬;将为下一次部署调查并修复该问题
猜你喜欢
  • 2016-11-06
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多