如何实现不可知的数据层?

时间:2013-11-23 10:27:09

标签: c# entity-framework design-patterns ado.net

我正在撰写概念验证应用程序。 当进入数据层时,我们需要能够连接到不同的数据库,并且可能会使用不同的技术

Ado.net(sqlCommand等..) 实体框架。 Nhibernate的。

我所说的是,无论是什么调用我们的RepositoryService类都无知使用的提供者.EG“实体框架,Raw Ado.Net NHibernate”等。

是否有一个示例或我可以查看的空壳或您的代码片段。 只是想知道你会怎么做。

Noddy实现给你一个想法,省略了可能的IOC等......:

 public class BusinessService
    {
        public List<CustomerDto> GetCustomers()
        {
            RepositoryService repositoryService=new RepositoryService();
            List<CustomerDto> customers = repositoryService.GetCustomers().ToList();
            return customers
        }
    }
    public class RepositoryService:IRepository
    {
        private string dbProvider;
        public RepositoryService()
        {
            //In here determine the provider from config file  EG Sql- EF etc.. and call the appriopiate repository
          //  dbProvider=???
        }
        public IEnumerable<CustomerDto> GetCustomers()
        {
             //Get the customers from the choosen repository
        }
    }
    public interface IRepository
    {
        IEnumerable<CustomerDto> GetCustomers();
    }
    public class SqlRepository : IRepository
    {
        public IEnumerable<CustomerDto> GetCustomers()
        {
            throw new NotImplementedException();
        }
    }

    public class EFRepository : IRepository
    {
        public IEnumerable<CustomerDto> GetCustomers()
        {
            throw new NotImplementedException();
        }
    }

    public class CustomerDto
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }

非常感谢

2 个答案:

答案 0 :(得分:1)

您应该更清楚自己的目标(以及您的目标)。访问数据会使某些存储库接口成为第一步。第二步是拥有数据表行的共享对象表示(如果要优化表映射,则为实体)。

场景背后的想法可能是:
a)我们不熟悉ORM技术,并希望在不冒风险的情况下尝试表现不佳。
b)我们的数据库非常庞大,我们操纵大量数据 c)我们的数据库包含数千个表 d)......

一般答案可能是:
1)尽可能使用选择的ORM 2)当表现不佳时,降级到ADO.NET甚至降级到存储过程。

实体框架和NHibernate使用高级实体映射抽象。你想用这个吗?如果没有,您可以使用像Dapper或PetaPoco这样的轻量级对象映射器。

ORM是将数据库访问代码的开发成本降低70%到80%的好方法(如果您只是读取数据,则为95%)。选择能够使用所有这些将确保您潜在的成本收益将会丢失。

PetaPoco对于第一个实验非常有趣,因为它包含C#项目中非常轻的映射器源代码,并使用易于理解的T4转换文件生成表对象(所有源代码都很小并包含在您的数据访问层中)。它的主要默认是它的作者去年有时间研究它。

如果ORM技术可以使程序更容易编写和扩展,它们就有缺点:

1)因为你在数据库之外工作,内存(或尚未持久化)对象和数据库数据之间的操作很容易变得非常昂贵:如果搜索有关数据库中一个对象的数据生成一个请求,则对对象集合将生成与集合中的项目一样多的请求。

2)由于高级ORM中的复杂变化跟踪机制,如果不处理这个问题,保存数据会变得非常慢。

3)ORM提供的功能越多,你的学习曲线越长。

答案 1 :(得分:0)

我通常完成此任务的方式是拥有存储库接口的不同具体实现,因此您可以拥有EFRepository或NHibernateRepository或AdoNetRepository或InMemoryDatabaseRepository实现。

只要您封装存储库的构造(通过工厂或依赖注入或其他),消耗存储库的类型就不必确切知道它们正在使用哪种类型的存储库。

相关问题