[英]DAL with dapper and C#
我有一個利用Dapper的數據訪問層,但不禁覺得它可以更加優雅。 DAL只是傳遞參數並根據模型的命名響應映射模型,因此該部分至少是直接的,但我討厭看起來重復的代碼。
這是一個例子
public IEnumerable<Product> ProductSearch(int? userId, DateTime? modifiedAfter, DateTime? modifiedBefore, Guid? productId)
{
IList<Product> products;
using (var connection = _connection.OpenConnection())
{
const string sproc = "dbo.stp_Product_Search";
products = connection.Query<JobProduct>(sproc, new
{
User_ID = userId,
Modified_After = modifiedAfter,
Modified_Before = modifiedBefore,
Product_ID = productId
}, commandType: CommandType.StoredProcedure)
.ToList();
}
return products;
}
我有很多這樣的代碼,但使用了不同的參數和實體。 有沒有人有任何好的例子?
感謝您的建議。 這就是我最終使用的意思,這意味着我不必使用語句來編寫每次使用少量代碼行時打開連接:
public class Repository<T> where T : class
{
protected readonly IComplianceConnection Connection;
public Repository(IComplianceConnection connection)
{
Connection = connection;
}
public IEnumerable<T> Get(string query, object arguments)
{
IList<T> entities;
using (var connection = Connection.OpenConnection())
{
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
}
return entities;
}
public T GetSingleOrDefault(string query, object arguments)
{
T entity;
using (var connection = Connection.OpenConnection())
{
entity =
connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).SingleOrDefault();
}
return entity;
}
public void Update(string query, object arguments)
{
using (var connection = Connection.OpenConnection())
{
connection.Execute(query, arguments, commandType: CommandType.StoredProcedure);
}
}
public int ExecuteScalar(string query, object arguments)
{
var id = 0;
using (var connection = Connection.OpenConnection())
{
id = connection.ExecuteScalar<int>(query, arguments, commandType: CommandType.StoredProcedure);
}
return id;
}
}
我最近在我的一個項目中使用了Dapper,我已經開始喜歡它非常簡單的事實。 這至少是它如此之快的部分原因。
但是我也理解你對重復的看法,如果你從代碼中的許多位置調用dbo.stp_Product_Search
,你不希望每次都映射參數並寫出整個查詢塊。
你可以看看把Dapper包裝在一個存儲庫中,但是我不喜歡這種方法,對我而言,它感覺就像是我已經成長為喜歡小巧玲瓏的裸骨。
我會考慮一個經理班。
public class ProductManager : IProductManager {
//Constructor code here
public IEnumerable<Product> ProductSearch(int? userId, DateTime? modifiedAfter, DateTime? modifiedBefore, Guid? productId)
{
using (var connection = _connection.OpenConnection())
{
const string sproc = "dbo.stp_Product_Search";
return connection.Query<Product>(sproc, new
{
User_ID = userId,
Modified_After = modifiedAfter,
Modified_Before = modifiedBefore,
Product_ID = productId
}, commandType: CommandType.StoredProcedure);
}
}
}
利用上面的類來調用特定於產品的可重用代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.