【发布时间】: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