views:

180

answers:

1

Hi folks,

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 repository 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)

+1  A: 

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();
Marc Gravell
I was hoping to NOT have the to provider known at this level, but implimented only INSIDE each providers namespace. Bascially, this extension method would be *persistence ignorant* and each persister/repository would then impliment the logic, how it see's fit. (my Take/Where examples where extream examples, used above .. by design). Does that make sense, Marc? (and thanks heaps for reading my question).
Pure.Krome
Also Marc, i found this blog post by you, interesting and relevant to this question: http://marcgravell.blogspot.com/2009/02/pragmatic-linq.html . Relating to this post, i *think* i'm trying to generate my own expression which will generate it's own SQL? (i hope i've used the correct terminology, here).
Pure.Krome
I don't think either is possible (in a generic way). LINQ-to-SQL allows you to issue custom TSQL, but not as part of an `Expression`. EF allows you to issue custom ESQL (a different syntax), and again not AFAIK as part of an `Expression`.
Marc Gravell
So what i really wanted to do, Marc, was to create an INLCUDE(string) extension method, and this will do a dataload for L2S and Include() in EF ... So you think it cannot be done?
Pure.Krome