【问题标题】:how to design Repository pattern to be easy switch to another ORM later?如何设计存储库模式以便以后轻松切换到另一个 ORM?
【发布时间】:2009-10-02 01:00:39
【问题描述】:

我是存储库模式的新手,但我尝试过,我的目标是做出一个设计,让我只需进行一些编辑“依赖注入或配置编辑”即可轻松切换到另一个 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 实体框架,或者 subsonic"

请提供简单的示例代码

【问题讨论】:

    标签: c# .net linq-to-sql design-patterns repository-pattern


    【解决方案1】:

    Inc Wall o' Text

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

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

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-11
      • 2010-12-02
      • 1970-01-01
      • 2014-08-26
      • 2015-11-07
      • 2013-08-30
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多