gpt4 book ai didi

c# - DAL 与 dapper 和 C#

转载 作者:行者123 更新时间:2023-11-30 14:09:07 25 4
gpt4 key购买 nike

我有一个使用 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;
}

我有很多这样的代码,但使用了不同的参数和实体。有没有人有任何好的例子?

最佳答案

谢谢大家的建议。这是我最后使用的方法,意味着我不必每次都编写 using 语句打开连接,从而使我的类代码行更少:

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

关于c# - DAL 与 dapper 和 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com