简体   繁体   中英

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. I have Install the Dapper into the class Library with Nuget. And i can see the reference in the references for 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. 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<> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM