C# 如何设计存储库模式以便以后轻松切换到另一个ORM?

C# 如何设计存储库模式以便以后轻松切换到另一个ORM?,c#,.net,linq-to-sql,design-patterns,repository-pattern,C#,.net,Linq To Sql,Design Patterns,Repository Pattern,我不熟悉存储库模式,但我尝试过,我的目标是设计一个只需少量编辑、依赖项注入或配置编辑即可轻松切换到另一个ORM,而无需触及其他解决方案层 我实现了以下目标: 代码如下: public interface IRepository<T> { T Get(int key); IQueryable<T> GetAll(); void Save(T entity); T Update(T entity); // Common data wi

我不熟悉存储库模式,但我尝试过,我的目标是设计一个只需少量编辑、依赖项注入或配置编辑即可轻松切换到另一个ORM,而无需触及其他解决方案层

我实现了以下目标:

代码如下:

public interface IRepository<T>
{
    T Get(int key);
    IQueryable<T> GetAll();
    void Save(T entity);
    T Update(T entity);
    // Common data will be added here
}
public interface ICustomerRepository : IRepository<Customer> 
{
    // Specific operations for the customers repository
}
public class CustomerRepository : ICustomerRepository
{
    #region ICustomerRepository Members

    public IQueryable<Customer> GetAll()
    {
        DataClasses1DataContext context = new DataClasses1DataContext();
        return from customer in context.Customers select customer;
    }

    #endregion

    #region IRepository<Customer> 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<Customer> repository = new CustomerRepository();
        var customers = repository.GetAll();

        this.GridView1.DataSource = customers;
        this.GridView1.DataBind();
    }
正如您在前面的代码中看到的,我现在使用的是LINQ to sql,正如您看到的,我的代码与LINQ to sql绑定,如何更改此代码设计以实现我的目标能够轻松地更改为另一个ORM,例如ADO.net实体框架或亚音速

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

Inc Wall o'Text

您所做的是正确的,您的代码将应用于每个存储库

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

例如,您决定切换到LINQtoEntities或ADO.NET

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

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

用外行的话说,存储库将以同样的方式为应用程序提供所需的数据。唯一的区别是如何将数据从数据库ADO.NET/Linq检索到其他内容

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