简体   繁体   English

使LINQ扩展方法适用于我的类

[英]Make LINQ extension methods apply to my class

I have a Repository class, which as a method FromStore<TEntity> as below: 我有一个Repository类,它作为方法FromStore<TEntity> ,如下所示:

IQueryable<TEntity> FromStore<TEntity>() where TEntity : class;

Using this I can do things like: 使用这个,我可以做以下事情:

MyRepository.FromStore<DatabaseModel>().SingleOrDefault(dm => dm.Id = Id);

Now, i'm thinking it's silly to make users of the class call FromStore when I could provide the SingleOrDefault method directly (you'd just have to specify the generic type parameter rather than it being inferred as is normally the case). 现在,我认为当我可以直接提供SingleOrDefault方法时,让类的用户调用FromStore是愚蠢的(你只需指定泛型类型参数而不是通常情况下推断它)。

So, I wrote a method as below: 所以,我写了一个方法如下:

public TEntity SingleOrDefault<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : class
{
    return FromStore<TEntity>().SingleOrDefault(filter);
}

Great! 大! Now I can do this: 现在我可以这样做:

MyRepository.SingleOrDefault<DatabaseModel>(dm => dm.Id = Id);

However, I want to do the same for all the linq extension methods. 但是,我想对所有linq扩展方法都这样做。
The only way I can think to do it currently is to create similar wrapper methods on my class for every single linq method. 我现在能想到的唯一方法是在我的类中为每个linq方法创建类似的包装器方法。

This seems silly, surely there's a better way? 这看起来很傻,肯定有更好的方法吗?

I was thinking could I somehow have my Repository class inherit the class that the linq extension methods extend, but they extend IQueriable<T> . 我想我可以以某种方式让我的Repository类继承linq扩展方法扩展的类,但它们扩展了IQueriable<T> My class doesn't implement that, because there's not just one T in the repository. 我的类没有实现它,因为存储库中不只有一个T


Can I get the linq extension methods to apply to my class somehow, even though I can't implement IQueryable<T> for a specific T ? 虽然我不能为特定的T实现IQueryable<T> ,但是我可以以某种方式将linq扩展方法应用于我的类吗?

You could implement it as an extension method for your repository interface. 您可以将其实现为存储库接口的扩展方法。

public static class RepositoryExtensions
{
    public static TEntity SingleOrDefault<TEntity>(
        this IRepository repository,
        Expression<Func<TEntity, bool>> filter
    )
    {
        return repository.FromStore<TEntity>().SingleOrDefault(filter);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM