尝试使用通用实体框架

时间:2012-12-19 13:35:08

标签: c# entity-framework generics

让我先说一下,我不确定这是否可行。我正在学习泛型,我的应用程序中有几个存储库。我正在尝试创建一个接受泛型类型的接口,并将其转换为所有存储库都可以继承的东西。现在回答我的问题。

public interface IRepository<T>
{
    IEnumerable<T> FindAll();
    IEnumerable<T> FindById(int id);
    IEnumerable<T> FindBy<A>(A type);
}

是否可以使用通用来确定要查找的内容?

public IEnumerable<SomeClass> FindBy<A>(A type)
{
    return _context.Set<SomeClass>().Where(x => x. == type); // I was hoping to do x.type and it would use the same variable to search.
}

为了澄清一点,我考虑成为一个字符串,int或我想要搜索的任何类型。我希望的是我可以说x.something其中某些东西等于传入的变量。

我可以使用

将任何存储库设置为我的dbcontext
public IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
    return base.Set<TEntity>();
}

任何建议?

2 个答案:

答案 0 :(得分:4)

如果您使用Expression<Func<T, bool>>代替A,请执行以下操作:

public interface IRepository<T>
{
    ... // other methods
    IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate);
}

您可以使用linq查询类型,并在调用存储库类的代码中指定查询。

public IEnumerable<SomeClass> FindBy(Expression<Func<SomeClass, bool>> predicate)
{
    return _context.Set<SomeClass>().Where(predicate);
}

并称之为:

var results = repository.FindBy(x => x.Name == "Foo");

鉴于它是一个通用表达式,您不必在每个存储库中实现它,您可以将它放在通用基础存储库中。

public IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)
{
    return _context.Set<T>().Where(predicate);
}

答案 1 :(得分:0)

我使用Interface和Abstract类的组合来实现这一点。

public class RepositoryEntityBase<T> : IRepositoryEntityBase<T>, IRepositoryEF<T> where T : BaseObject
 // 
public RepositoryEntityBase(DbContext context)
    {
        Context = context;
//etc

public interface IRepositoryEntityBase<T> : IRepositoryEvent where T : BaseObject //must be a model class we are exposing in a repository object

{
    OperationStatus Add(T entity);
    OperationStatus Remove(T entity);
    OperationStatus Change(T entity);
   //etc

然后派生类可以有一些特定于Object的方法,或者实际上没有任何东西,只需要工作

public class RepositoryModule : RepositoryEntityBase<Module>, IRepositoryModule{
    public RepositoryModule(DbContext context) : base(context, currentState) {}
}
//etc