作者:手机用户2602880045 | 来源:互联网 | 2023-05-26 15:41
我正在开发一个现有的应用程序,首先使用Generic Repo模式和EF6数据库.我正在调用一个存储过程,它返回一个复杂类型,它不是我实体模型中的现有实体,因此我不确定要给出的类型.
这是我从服务层调用sp的方式
_unitOfWork.Repository()
.SqlQuery("sp_Get @FromDateTime, @ToDateTime, @CountyId",
new SqlParameter("FromDateTime", SqlDbType.DateTime) { Value = Request.FromDateTime },
new SqlParameter("ToDateTime", SqlDbType.DateTime) { Value = Request.TripToDateTime },
new SqlParameter("CountyId", SqlDbType.Int) { Value = Convert.ToInt32(Request.County) }
).ToList();
我是否在数据层中创建实体以映射到或返回复杂类型的存储过程的最佳方法是什么.如果是这样,是否需要自定义映射,或者仅仅是创建Entity类的情况
谢谢
1> octavioccl..:
如果你有一个带有这些字段的实体你可以调用上面显示的SqlQuery方法,如果没有,那么我建议创建一个新的类来映射结果:
public class Result
{
public int CountyId { get; set; }
public DateTime FromDateTime { get; set; }
public DateTime ToDateTime { get; set; }
}
我不知道在你的情况下如何实现UnitOfWork模式,但我认为你可以访问你的Context.在您的UnitOfWork
班级中,您可以创建如下通用方法:
public class UnitOfWork
{
private YourContext Context { get; set; }
public DbRawSqlQuery SQLQuery(string sql, params object[] parameters)
{
return Context.Database.SqlQuery(sql, parameters);
}
}
这样,您可以执行您的商店程序,如下所示:
var result= _unitOfWork.SqlQuery("sp_Get @FromDateTime, @ToDateTime, @CountyId",
new SqlParameter("FromDateTime", SqlDbType.DateTime) { Value = Request.FromDateTime },
new SqlParameter("ToDateTime", SqlDbType.DateTime) { Value = Request.TripToDateTime },
new SqlParameter("CountyId", SqlDbType.Int) { Value = Convert.ToInt32(Request.County) }
).ToList();
2> saille..:
存储库模式的目的是抽象出数据的存储和检索,以保护您的客户端代码,例如业务层(在您的情况下为服务层),而不需要知道有关数据如何持久化的任何信息.例如,SQL语句只存在于Repository类中,而不会影响整个代码.
如果您将SQL,存储过程名称和参数公开给您的客户端代码,那么您从Repository Pattern中得不到多少好处,如果您根本无法将其称为存储库.您失去了能够模拟存储库并独立于数据访问层测试业务层的好处.这意味着需要集成测试(需要完整的数据库实例)来验证业务逻辑.
考虑重新分解,以便您拥有一个CountryRepository类,该类具有返回Country实体或类似的GetCountry(int CountryId,DateTime fromDate,DateTime toDate)方法.我想你会同意,与你问题中的代码相比,你的代码的可读性会大大提高.
public class CountryRepository
{
public Country GetCountry(int CountryId, DateTime fromDate, DateTime toDate)
{
// EF or ADO.NET code here
}
}
然后客户端代码将是例如
var c = unitOfWork.CountryRepository.GetCountry(1, DateTime.Now.AddYears(-1), DateTime.Now);
另见这个问题