繁体   English   中英

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

[英]how can I implement an agnostic data layer?

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

Ado.net(sqlCommand等。)实体框架。 冬眠

我的意思是,无论调用我们的RepositoryService类,对于使用的提供程序都是无知的。例如,“ Entity Framework,Raw Ado.Net NHibernate”等。

是否有示例或我可以看的空壳或您的代码段。 只是给一个想法,你将如何去做。

点头实施让您有个想法,省略了可能的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; }
    }

非常感谢

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

幕后的想法可能是:
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提供的功能越多,您的学习曲线就越长。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM