Dapper:必须在Select命令中声明标量变量

时间:2018-06-19 16:04:46

标签: c# sql dapper

以下查询

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=****;");

2 个答案:

答案 0 :(得分:2)

经过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"));
    }
}

答案 1 :(得分:1)

经过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; }
}

像“某些登录名”那样的登录工作正常,并且也返回预期结果。