如何设计Repository模式以便以后轻松切换到另一个ORM?

我是存储库模式的新手,但我尝试过,我的目标是制作一个设计,只需一些编辑“dependency injection或配置编辑”就可以轻松地切换到另一个ORM,而无需触及其他解决方案层。

我达到了这个实现: 替代文字

这是代码:

public interface IRepository { T Get(int key); IQueryable GetAll(); void Save(T entity); T Update(T entity); // Common data will be added here } public interface ICustomerRepository : IRepository { // Specific operations for the customers repository } public class CustomerRepository : ICustomerRepository { #region ICustomerRepository Members public IQueryable GetAll() { DataClasses1DataContext context = new DataClasses1DataContext(); return from customer in context.Customers select customer; } #endregion #region IRepository Members public Customer Get(int key) { throw new NotImplementedException(); } public void Save(Customer entity) { throw new NotImplementedException(); } public Customer Update(Customer entity) { throw new NotImplementedException(); } #endregion } 

我的aspx页面中的用法:

 protected void Page_Load(object sender, EventArgs e) { IRepository repository = new CustomerRepository(); var customers = repository.GetAll(); this.GridView1.DataSource = customers; this.GridView1.DataBind(); } 

正如您在上面的代码中看到的那样,我现在使用LINQ to sql,并且如您所见,我的代码与LINQ to sql相关联,如何更改此代码设计以实现我的目标“能够轻松地更改为另一个ORM,例如到ADO.netentity framework,或亚音速“

请提供简单的示例代码建议

Inc Wall o’Text

你正在做的是对的,你的代码将应用于每个存储库。

正如您所说,存储库模式的目的是让您可以交换数据传递到应用程序的方式,而无需在应用程序(UI /交付层)中重构代码。

例如,您决定切换到Linq to Entities或ADO.NET。

您所需要的只是为您将要使用的ORM编写代码(让它inheritance正确的接口),然后让您的代码使用该存储库。 当然,您需要替换旧存储库的所有引用或重命名/替换旧的ORM存储库,以便您的应用程序使用正确的存储库(除非您使用某种类型的IoC容器,您将在其中指定要传递的存储库) 。

您的应用程序的其余部分将继续正常运行,因为您用于获取/编辑数据的所有方法都将返回正确的对象。

在外行的术语中,存储库将以相同的方式为您的应用程序提供所需的数据。 唯一的区别是如何从数据库中检索数据(ADO.NET/Linq等等)

让您的类inheritance存储库接口是一个硬约束,确保它们以统一的方式输出数据,这与您的应用程序使用它的方式一致。