[英]Not able to use Query with Dapper in Class library
I am very new bee for Dapper ORM, i am just trying to create a class library for Business logic with Dapper. 我是Dapper ORM的新手,我只是想用Dapper创建业务逻辑的类库。 I have Install the Dapper into the class Library with Nuget. 我已经使用Nuget将Dapper安装到类库中。 And i can see the reference in the references for Dapper(1.50.2). 我可以在Dapper(1.50.2)的参考资料中看到该参考资料。 Now i write following code, in which i am not able to access "Query". 现在,我编写以下代码,其中无法访问“查询”。
namespace ClassLibrary1
{
public class Class1
{
static IDbConnection db2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConnString"].ConnectionString);
public Class1()
{
}
public List<dynamic> GetRecords()
{
string query = "select * from contacts";
return (List<dynamic>)db2.Query<dynamic>(query);
}
}
}
Please help me.. and tell me what i am doing wrong. 请帮助我..并告诉我我做错了。
You need to include the extensions on the Dapper
namespace. 您需要在Dapper
名称空间上包括扩展名。 Just add: 只需添加:
using Dapper;
On top of your file 在文件之上
Apart from that, a more correct way to write the class 除此之外,更正确的方式编写类
namespace ClassLibrary1 {
using Dapper;
public class Class1 {
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["SqlServerConnString"].ConnectionString;
public Class1() {}
public List<dynamic> GetRecords() {
string query = "select * from contacts";
using (var db = new SqlConnection(connectionString))
return db.Query<dynamic>(query).AsList();
}
}
}
This handles dispose of the SqlConnection
object and .AsList
method saves from typecasting IEnumerable<>
to List<>
. 这将处理SqlConnection
对象的处理,并将.AsList
方法从类型转换IEnumerable<>
保存到List<>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.