【问题标题】:MVC 6 How can I include a BaseRepository in my controller classMVC 6 如何在我的控制器类中包含 BaseRepository
【发布时间】:2016-02-01 14:02:22
【问题描述】:

我正在使用 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();

        });
    }
}

我遇到问题的部分是这个 public class PersonRepository : BaseRepository 因为 Asp.Net 控制器以 public class 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 方法,因为它为所有类型的错误提供了任何建议?

【问题讨论】:

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


    【解决方案1】:

    为什么使用继承而不是组合?像这样的东西呢:

    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 中的依赖注入。

    【讨论】:

      【解决方案2】:

      您必须从“控制器”中集成“BaseRepository”。我认为这对你有用。然后只需使用以下代码:

      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();
      
          });
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 2014-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多