开发者

Can I do this with an IQueryable<T>?

开发者 https://www.devze.com 2022-12-12 11:02 出处:网络
is it possible to add an extension method to IQueryable<T> and then, for my Linq2Sql or EF or NHibernate or LinqToObjects, define it\'s functionality / how each repos开发者_运维知识库itory will

is it possible to add an extension method to IQueryable<T> and then, for my Linq2Sql or EF or NHibernate or LinqToObjects, define it's functionality / how each repos开发者_运维知识库itory will impliment this method / translate this method to some sql?

For example, imagine I want the following :-

var result = (from q in db.Categories()
              where q.IWishIKnewHowToCode("hi")
              select q).ToList();

now, the code for the extension method IWishIKnewHowToCode() will differ when it's L2S, compared to EF or LinqToObjects, etc.

I'm not talking about a Pipes and Filters, here. That I know how to do that.

So imagine that, if this was L2S, then that method would do a linq Where clause but if the repository was .. say ... LinqToObjects, it would do a Take(10).

Is this possible?

(I'm not too sure what it's officially called ... about what I'm wanting to do)


That is pretty evil, but the closest I can think would be to special-case the provider:

public static class Test
{
    public static IQueryable<T> IWishIKnewHowToToCode<T>(
        this IQueryable<T> data, string something)
       // perhaps "where T : SomeBaseTypeOrInterfaceForThePredicate"
    {
        switch (data.Provider.GetType().Name)
        {
            case "Foo": return data.Take(10);
            case "Bar": return data.Where(somePredicate);
            default: return data;
        }
    }
}

(obviously there are other ways to switch on Type).

Then use via fluent syntax (not query syntax):

var result = db.Categories().IWishIKnewHowToCode("hi").ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号