是否可以从 POCO 调用数据层/存储库
本文关键字:存储 数据 调用 POCO 是否 | 更新日期: 2023-09-27 17:57:14
我正在尝试弄清楚如何为我的购物车设置一个干净的架构,而不会过度构建它或最终得到一个乏力的领域模型。 现在我只想使用没有任何ORM框架的标准ADO数据库逻辑。 (我也在学习EF4.1,但还不够好,无法在生产中使用)
理想情况下,我只会为每个业务对象/实体提供一个 POCO 和一个将处理持久性的存储库/数据类。 为了简单起见,我正在考虑将 POCO 紧密耦合到数据层,它将返回 POCO。 如果我也将DTO添加到组合中,那么我最终为每个区域(gc,订单,项目,付款等)提供5-6个类文件,这对于一个简单的应用程序来说似乎太多了。 我以后总是可以改进的。
我正在研究的第一堂课是礼券。 其中一种方法是创建新的 GC。 在这种方法中,我需要查询数据库以确保系统中尚不存在新代码。 是否可以在此方法中仅调用数据层/存储库?
数据层/存储库应该是静态的吗? 我应该只通过 POCO 本身公开它吗?
我是否应该完全删除数据层,而直接在我的 POCO(活动记录样式)中进行数据调用?
我需要一个简单的架构,它可以让我在不影响事情复杂化的情况下将关注点分开。 至少在未来几年内,数据库提供程序和表结构不会改变。
这里有一些代码..只需要弄清楚零件的去向。
public GiftCertificateModel
{
public int GiftCerticiateId {get;set;}
public string Code {get;set;}
public decimal Amount {get;set;}
public DateTime ExpirationDate {get;set;}
public void Redeem(string code, decimal amount)
{
//need to validate the input
//need to insert a record to the transaction log table (call the repo or does this entire method need to be in the repo?)
}
public void GetNewCode()
{
//need to create random alpha num code
//need to make sure the code is unique in the db... (again, (call the repo or does this entire method need to be in the repo?
}
}
public GiftCertificateRepo : DALBase (DALBase has methods for connecting, etc)
{
//mapping code here to map SQLDataReader values to GiftCertificateModel properties
//i can also setup separate DTOs if it makes more sense...
//should the repo be static?
public static GiftCertificateModel GetById(int GiftCertificateId)
{
//call db to get one and return single model
}
public static bool IsUnique(string code)
{
//call db to see if any records exists for code
}
public static List<GiftCertificateModel> GetMany()
{
//call db to get many and return list
}
public static void Save(GiftCertificateModel gc)
{
//call db to save
}
}
电话代码:
GiftCertificateModel gc = new GiftCertificateModel();
gc.Code = gc.GetNewCode(); //do i call the is unique here or in the GetNewCode method?
gc.Amount = 10;
gc.ExpirationDate = "1/1/2012";
GiftCertificateRepo.Save(gc);
根据定义,POCO 是持久性无知的,即它不知道这一点以及如何持久化。
如果您将业务对象耦合到存储库或持久性层,根据您的情况,这可能完全没问题,但它不再是 POCO。
几种系统/意识形态,但他们都同意持久性不是业务类的一部分。 创建一个单独的数据访问层来存储和检索您的 POCO。
通过将 POCO(数据表示)与存储库对象(数据存储/检索方式的表示)分开,您将能够在未来更轻松地从 ADO 切换到更高级的 ORM 系统 - 这些代码更改将被隔离到一个地方。
更好的是,定义一个 IRepository 接口并让您的 ADO repostiory 类实现它。 然后,您的应用程序应仅与 IRepository 一起使用,从而在将来更轻松地测试或切换存储库实现。