Dapper:必须在 Select 命令中声明标量变量
Posted
技术标签:
【中文标题】Dapper:必须在 Select 命令中声明标量变量【英文标题】:Dapper : must declare the scalar variable in Select command 【发布时间】:2018-06-19 16:04:45 【问题描述】:以下查询
Connection.Query<User>("select * from User where Login=@login and Passwd=@passwd", new login = _login, passwd=_passwd)
返回以下错误
必须声明标量变量@login
用户模型:
public class User
public int Id get; set;
public string Login get; set;
public string Passwd get; set;
更新:
我的问题来自 SQL 连接
我的连接字符串是
new OleDbConnection(@"Provider=sqloledb;Data Source=MYPC\SQLEXPRESS;Initial Catalog=MYDB;User Id=sa;Password=****;");
我已经改成
new SqlConnection(@"Data Source=MYPC\SQLEXPRESS;Initial Catalog=MYDB;User Id=sa;Password=****;");
【问题讨论】:
你用的是什么数据库? 当你停在断点处时,_login
有值吗?
@MarioGuadanhim 这在任何 sql 数据库引擎中都是大罪。永远不要连接字符串来构建 sql 命令
@Steve 我正在使用 SQL Server
【参考方案1】:
用 SQL Server 测试,似乎工作正常:
[Test]
public void simple_select_test()
using (var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=test"))
var result = conn.Query<User>(
"select * from (select Id = 420, Login = 'foo', Passwd = 'bar') a where Login=@login and Passwd=@passwd",
new login = "foo", passwd = "bar").First();
Assert.That(result.Login, Is.EqualTo("foo"));
Assert.That(result.Passwd, Is.EqualTo("bar"));
【讨论】:
【参考方案2】:用 PostgreSQL 测试,一切正常:
class Program
static void Main(string[] args)
var connectionString = "User ID=postgres;Password=pass;Host=localhost;Port=5432;Database=TestUser;";
var connection = new NpgsqlConnection(connectionString);
var _login = "someLogin";
var _passwd = "somePass";
connection.Open();
var result = connection.Query<User>("select * from public.users where login=@login and password=@passwd", new login = _login, passwd = _passwd );
connection.Close();
foreach (var item in result)
Console.WriteLine($"Id: item.Id. Login: item.Login");
public class User
public int Id get; set;
public string Login get; set;
public string Password get; set;
像“一些登录”这样的登录工作正常,并且也返回预期的结果。
【讨论】:
以上是关于Dapper:必须在 Select 命令中声明标量变量的主要内容,如果未能解决你的问题,请参考以下文章