需要弄清楚Repository类的T是为了什么

时间:2011-04-26 20:36:25

标签: asp.net-mvc c#-4.0 .net-4.0 repository-pattern

我有类Repository,并且基于T我想在我的构造函数中为类型T..创建objectset ...这是我到目前为止所拥有的..

public static class Repository<T> : IDisposable
    where T : class
{
    private DeltaDBEntities context;
    private ObjectSet<T> objectset;
    public Repository()
    {
        this.context =  new DeltaDBEntities();
        switch
        {
            case T = typeof(ViewModels.Company):
                this.objectset = context.Companies;
                break;
        }

        this.objectset = context.Set
    }

2 个答案:

答案 0 :(得分:1)

如果您的DeltaDBEntities继承自ObjectContext,则可以使用其通用方法CreateObjectSet<T>()

public class Repository<T> where T : class
{
    private DeltaDBEntities context;
    private ObjectSet<T> objectset;

    public Repository()
    {
        this.context = new DeltaDBEntities();
        this.objectset = context.CreateObjectSet<T>();
    }
}

答案 1 :(得分:0)

不确定您要实现的目标以及为什么使用泛型来编译在编译时未知的内容,但您可以尝试以下方法:

public class Repository<T> : IDisposable where T : class
{
    private DeltaDBEntities context;
    private ObjectSet<T> objectset;

    public Repository()
    {
        this.context = new DeltaDBEntities();
        if (typeof(T) == typeof(ViewModels.Company))
        {
            this.objectset = context.Companies;
        }
        else if (typeof(T) == typeof(ViewModels.SomeOtherClass))
        {
            this.objectset = context.SomethingElse;
        }
        else
        {
            this.objectset = context.Set;
        }
    }

    public void Dispose()
    {
        // TODO: implement IDisposable
    }
}

另请注意,静态类无法实现接口,因此Repository<T>不应该是静态的。