我有复杂的应用程序到数据库的操作,我正在使用Dapper Micro-ORM,我想做松散耦合的代码。请建议如何在dapper中使用接口而不是类。我有以下代码:
public IEnumerable<Category> Find()
{
using (IDbConnection _conn = GetConnection)
{
_conn.Open();
return _conn.Query<Category>("usp_Category", commandType: CommandType.StoredProcedure);
}
}我想替换为
public IEnumerable<ICategory> Find()
{
using (IDbConnection _conn = GetConnection)
{
_conn.Open();
return _conn.Query<ICategory>("usp_Category", commandType: CommandType.StoredProcedure);
}
}发布于 2016-07-17 14:56:01
您尝试对Dapper和C#执行的操作是不正确的:
_conn.Query<ICategory>("usp_Category", commandType: CommandType.StoredProcedure);您正在尝试获取IEnumerable<ICategory>,这是不会成功的,因为ICategory是一个interface,并且不能像您预期的那样填充,所以您最多只能获取:IEnumerable<Category>。您不能像初始化具体类一样初始化ICategory interface,这是不可能的
ICategory ic = new ICategory();要理解您需要理解interface和concrete类之间的区别以及它们的用法,IEnumerable<ICategory>不是正确的用法,也不能通过任何方式获取
发布于 2016-07-29 04:30:28
尽管您希望松散地耦合代码,但在某些情况下,您必须为每个ICategory实例创建一个具体的实现。
在您提供的示例中,Dapper调用将发生这种情况。Dapper将从查询中获取数据(通过IDbConnection实现类型的连接,因此存在一些松散耦合),并将每一行转换为Category实例。
"Find“方法将返回一个IEnumerable,由这些具体实现组成。但是,因为IEnumerable是协变的,所以可以将IEnumerable转换为IEnumerable。
这允许" Find“方法的返回类型为IEnumerable,这意味着该方法的使用者只需要知道返回一组ICategory实现(Dapper需要知道要填充的具体类型,而Find方法的调用者不需要知道将返回什么ICategory实现)。
您的代码只需稍作更改:
public IEnumerable<ICategory> Find()
{
using (IDbConnection _conn = GetConnection())
{
return _conn.Query<Category>("usp_Category", commandType: CommandType.StoredProcedure);
}
}(请注意,我删除了_conn.Open();行,因为Dapper将为您打开连接,如果它尚未打开的话)。
发布于 2016-09-19 15:39:38
我们可以使用泛型实现来代替松散耦合的代码,它将通过泛型存储库模式使用您的ORM存储库。
public virtual IEnumerable<T> GetAll()
{
IEnumerable<T> items = null;
using (DbConnection cn = this.Connection)
{
cn.Open();
items = cn.Query<T>("Select * from [TableName]");
}
return items;
}您可以在GitHub link下找到使用ASP.NET核心进行通用实现的库
https://stackoverflow.com/questions/38418558
复制相似问题