如何建立一个通用的存储库 [英] How to build a generic repository

查看:115
本文介绍了如何建立一个通用的存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展与NHibernate在ASP.NET MVC的Web应用程序。

I'm developing a web application in ASP.NET MVC with NHibernate.

,我使用的存储库我的课。

Based in articles and tutorials I've found at Google, I'm using Repository for my classes.

我有10个班和10个仓库。今天,我想通了,90%的矿山资源库是完全彼此相等,除了类。这是一个例子:

I have 10 classes and 10 repositories. Today I figured out that 90% of mine repositories are exactly equal each other, except for the class. This is one example:

public class PromocaoRepository:IPromocaoRepository {
    private ISession Session;

    public PromocaoRepository() {
        this.Session = NHibernateSessionFactory.OpenSession();
    }

    public void Add(Promocao promocao) {
        using(ITransaction transaction = this.Session.BeginTransaction()) {
            this.Session.Save(promocao);
            transaction.Commit();
        }
    }

    public void Edit(Promocao promocao) {
        using(ITransaction transaction = this.Session.BeginTransaction()) {
            this.Session.Update(promocao);
            transaction.Commit();
        }
    }

    public void Remove(Promocao promocao) {
        using(ITransaction transaction = this.Session.BeginTransaction()) {
            this.Session.Delete(promocao);
            transaction.Commit();
        }
    }

    public Promocao GetById(int id) {
        return this.Session.Get<Promocao>(id);
    }

}

有一种方法可以做一种通用的存储库巫我可以在我的所有的类使用?

There is a way to do a kind of generic repository witch I can use in all my classes?

如果有可能,我应该在的情况下,我需要一个特定的类中创建一个特定的方法?

If it's possible, what should I do in case I need to create a particular method for an specific class?

推荐答案

您应该做一个通用存储库中,您可以在一般情况下使用,而且如果需要特定类的任何额外方法,通过继承添加。用你的例子:

You should make a generic repository, which you can use in the general case, and if any extra methods is needed for a particular class, add it by using inheritance. Using your example:

public class GenericRepository<TEntity> :IGenericRepository<TEntity> {
    private ISession Session;

    public GenericRepository() {
        this.Session = NHibernateSessionFactory.OpenSession();
    }

    public void Add(TEntity instance) {
        using(ITransaction transaction = this.Session.BeginTransaction()) {
            this.Session.Save(instance);
            transaction.Commit();
        }
    }

    /* other methods */ 
}

public class SpecificRepository : GenericRepository<SpecificEntity>, ISpecificRepository 
{
    public void SpecialQuery()  { /* added method implementation */ }
}

这篇关于如何建立一个通用的存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆