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

Amr*_*rhy 5 .net c# design-patterns repository-pattern linq-to-sql

我是存储库模式的新手,但我尝试过,我的目标是制作一个设计,让我可以轻松地使用一些编辑"依赖注入或配置编辑",以便能够切换到另一个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
}
Run Code Online (Sandbox Code Playgroud)

我的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();
    }
Run Code Online (Sandbox Code Playgroud)

正如你在前面的代码中看到现在我使用LINQ to SQL语句,当你看到我的代码被绑定到LINQ到SQL,如何改变这种代码设计,实现我的目标"能够改变到另一个ORM伊斯利,例如到ADO.net实体框架,或亚音速"

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

Oma*_*mar 3

公司文字墙

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

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

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

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

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

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

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