从POCO调用数据层/仓库可以吗?

问题描述

| 我试图弄清楚如何为我的购物车设置一个干净的体系结构,而不用过度设计它或最终导致贫乏的领域模型。现在,我只想使用没有任何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(数据表示)与存储库对象(数据的存储/检索表示)分开,将来您将能够更轻松地从ADO切换到更高级的ORM系统-这些代码更改将是隔离到一个地方。 更好的是,定义一个IRepository接口并让您的ADO repostiory类实现它。然后,您的应用程序应仅与IRepository一起使用,从而使将来测试或切换存储库实现更加容易。     ,根据定义,POCO不了解持久性,即它不知道持久性和持久性。 如果将业务对象耦合到存储库或持久性层,根据情况的不同可能会很好,但是不再是POCO。     ,那里有几种系统/思想,但是他们都同意持久性不是业务类别的一部分。制作一个单独的数据访问层以存储和检索您的POCO。