使用 MySql Connector/Net 和 Dapper 的非参数 SQL 变量?
下面的代码会生成以下错误:
必须定义参数“@ID”。
我是否做错了什么,或者是否可以在 MySQL 的 SQL 查询中使用不是 Dapper 参数的变量?
在此示例中,@Slug 是 Dapper 参数,但 @ID 不是。我正在使用 MySQL,所以我不需要定义 @ID - 它是在第一次使用时定义的。
var sql = @"SELECT @ID := id, slug, Title, Text FROM posts WHERE slug = @Slug; SELECT * FROM comments where postid = @ID;";
using (var connection = GetOpenConnection())
{
var posts = connection.QueryMultiple(sql, new { Slug = slug })
.Map<Post, Comment, int>
(
Post => Post.ID,
Comment => Comment.ID,
(post, comments) => { post.Comments = comments; }
);
return posts.FirstOrDefault();
}
The code below generates the following error:
Parameter '@ID' must be defined.
Am I doing something wrong or is not it possible to use variables in the SQL query with MySQL which aren't Dapper parameters?
In this example, @Slug is a Dapper parameter, but @ID is not. I'm using MySQL so I don't need to DEFINE @ID - it get's defined in the first use.
var sql = @"SELECT @ID := id, slug, Title, Text FROM posts WHERE slug = @Slug; SELECT * FROM comments where postid = @ID;";
using (var connection = GetOpenConnection())
{
var posts = connection.QueryMultiple(sql, new { Slug = slug })
.Map<Post, Comment, int>
(
Post => Post.ID,
Comment => Comment.ID,
(post, comments) => { post.Comments = comments; }
);
return posts.FirstOrDefault();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实证明“MySql Connector/Net”生成了错误。
为了将非参数 SQL 变量与 MySql Connector/Net 一起使用,您必须将以下选项添加到连接字符串中:
请参阅:http://blog.tjitjing.com/index.php/ 2009/05/mysqldatamysqlclientmysqlexception-parameter-id-must-be-define.html
It turns out "MySql Connector/Net" generates the error.
In order to use Non-parameter SQL Variables with MySql Connector/Net, you have to add the following option to your connection string:
See: http://blog.tjitjing.com/index.php/2009/05/mysqldatamysqlclientmysqlexception-parameter-id-must-be-defined.html
我不认为这是一个短小精悍的问题; dapper 只是接受您提供的 SQL,并添加它在 SQL 中明显看到的“args”对象中的任何成员。
调查此问题的方法是尝试直接使用 DbCommand 运行相同的命令 - 我的猜测是它会失败。将会有一些 SQL 技巧来使其工作,但这是你和 MySQL 之间的事情。 dapper 所做的就是:
它不会触及“ID”,而且它是正确的但事实并非如此。
I don't think this is a dapper issue; dapper just takes the SQL you offer, and adds any members from the "args" object that it obviously see in the SQL.
The way to investigate this is to try running the same with DbCommand directly - my guess is that it will fail identical. There is going to be some SQL trick to make it work, but that is between you and MySQL. All dapper is doing is:
it doesn't touch "ID", and it is correct that it doesn't do so.
您需要在 sql 代码中声明 ID 变量:
You need to declare the ID variable in your sql code: