MVC 6如何在我的控制器类中包含BaseRepository

时间:2016-02-01 05:47:55

标签: asp.net-mvc asp.net-core asp.net-core-mvc dapper

我使用ORM连接到数据库,它被称为dapper。它的问题是它的数据库调用是同步的,我最近找到了一种方法,通过遵循这个简短的教程http://www.joesauve.com/async-dapper-and-async-sql-connection-management/使其异步。我的问题是如何将此BaseRepository引入我的Controller类?这是该网站上的代码,它与我的相同

BaseRepository-这个代码中没有问题

 public abstract class BaseRepository 
   {

private readonly string _ConnectionString;

protected BaseRepository(string connectionString) 
{
    _ConnectionString = connectionString;
}

protected async Task<T> WithConnection<T>(Func<IDbConnection, Task<T>> getData) 
{
    try {
        using (var connection = new SqlConnection(_ConnectionString)) {
            await connection.OpenAsync(); // Asynchronously open a connection to the database
            return await getData(connection); // Asynchronously execute getData, which has been passed in as a Func<IDBConnection, Task<T>>
        }
    }
    catch (TimeoutException ex) {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL timeout", GetType().FullName), ex);
    }
    catch (SqlException ex) {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL exception (not a timeout)", GetType().FullName), ex);
    }
}

}

现在他就像这样把它带来了

public class PersonRepository : BaseRepository
{
    public PersonRepository(string connectionString): base (connectionString) { }

    public async Task<Person> GetPersonById(Guid Id)
    {
        return await WithConnection(async c => {

            // Here's all the same data access code,
            // albeit now it's async, and nicely wrapped
            // in this handy WithConnection() call.
            var p = new DynamicParameters();
            p.Add("Id", Id, DbType.Guid);
            var people = await c.QueryAsync<Person>(
                sql: "sp_Person_GetById", 
                param: p, 
                commandType: CommandType.StoredProcedure);
            return people.FirstOrDefault();

        });
    }
}

我遇到问题的部分是公共类PersonRepository:BaseRepository ,因为Asp.Net控制器以公共类HomeController:Controller 开头,我需要访问使用WithConnection 方法来实现此功能。我的控制器看起来像这样

 public class HomeController : Controller
    {

        public class ConnectionRepository : BaseRepository
        {
            public ConnectionRepository(string connectionString) : base(connectionString) { }

        }
      public async Task<ActionResult> topfive()
            {
    // I get Error on WithConnection as it can't see the BaseRepository
                return await WithConnection(async c =>
                {


                    var topfive = await c.QueryAsync<Streams>("select * from streams ").ToList();
                return View(topfive);
                });

 }
            }

我显然无法用BaseRepository覆盖我的ActionResult方法,因为它给出了所有类型的错误任何建议?

2 个答案:

答案 0 :(得分:2)

为什么使用继承而不是合成?怎么样:

public class PersonRepository : BaseRepository
{
    public PersonRepository(string connectionString): base (connectionString) { }

    public async Task<Person> GetPersonById(Guid Id)
    {
        return await WithConnection(async c => {

            // Here's all the same data access code,
            // albeit now it's async, and nicely wrapped
            // in this handy WithConnection() call.
            var p = new DynamicParameters();
            p.Add("Id", Id, DbType.Guid);
            var people = await c.QueryAsync<Person>(
                sql: "sp_Person_GetById", 
                param: p, 
                commandType: CommandType.StoredProcedure);
            return people.FirstOrDefault();

        });
    }
    }

        public class ConnectionRepository : BaseRepository
        {
            public ConnectionRepository(string connectionString) : base(connectionString) { }

        }
      public async Task<List<TopFileClass>> topfive()
            {
    // I get Error on WithConnection as it can't see the BaseRepository
                return await WithConnection(async c =>
                {


                    var topfive = await c.QueryAsync<Streams>("select * from streams ").ToList();
                return topfive;
                });

 }

public class HomeController : Controller
{
   private readonly PersonRepository _repo;

   public HomeController(PersonRepository repo)
   {
       _repo = repo;
   }

   public async Task<ActionResult> TopFive() 
   {
       var top5 = await _repo.topfive();
       return View(top5);
   }
}

如果您不熟悉如何使存储库自动注入构造函数,请阅读MVC 6中的依赖注入。

答案 1 :(得分:1)

你必须在&#34; BaseRepository&#34;来自&#34; Controller&#34;。我认为这对你有用。然后只需使用以下代码:

public abstract class BaseRepository : Controller 
{ 
// do you work
}


public class PersonRepository : BaseRepository
{
public PersonRepository(string connectionString): base (connectionString) { }

public async Task<Person> GetPersonById(Guid Id)
{
    return await WithConnection(async c => {

        // Here's all the same data access code,
        // albeit now it's async, and nicely wrapped
        // in this handy WithConnection() call.
        var p = new DynamicParameters();
        p.Add("Id", Id, DbType.Guid);
        var people = await c.QueryAsync<Person>(
            sql: "sp_Person_GetById", 
            param: p, 
            commandType: CommandType.StoredProcedure);
        return people.FirstOrDefault();

    });
   }
}