Strongly typed include in EF

The other day I was talking to my old teacher, Jon Wiberg, at "Ljud & Bild skolan". He told me that he had built a extension for the entity framework that enables you to use a strongly typed version of the ".Include()" method in Entity Framework using a lambda expression. I think it´s a lot better approach then just using "magic strings" as a compiletime error is allways better then a runtime error.

So I tought I´d share the code with you here. First we have a static class with a method that gets the name of the property that the expression is pointing at:

public static class Nameof<T>
{
    public static string Property<TProp>(
                                    Expression<Func<T, TProp>> expr)
    {
        var body = expr.Body as MemberExpression;
        if (body == null)
            throw new ArgumentException(
                       "Parameter expr must be a memberexpression");


        return body.Member.Name;
    }
}

And here is the extension method itself:

public static ObjectQuery<T> Include<T, Tprop>(
              this ObjectQuery<T> q, Expression<Func<T, Tprop>> expr)
{
    return q.Include(Nameof<T>.Property<Tprop>(expr));
}

I implementet this in a project that I´m working on, and it works nicely. Say NO to magic strings. Any credit goes to Jon as I´m only sharing his code.

kick it on DotNetKicks.com
Shout it

Comments

Add comment

Name:

Mail:

Website:

Comment:


<< [1] >>
  • 1 years ago by Armin Sander

     Great, thanks for sharing!

    I had a similar idea to misuse expressions. In this case to avoid typing setters. Expanding this idea you are able to effectively "reference" properties by dynamically generating a getter and a setter Func<> and Action<>. Sure you could use reflections, but at a 100 fold spead penalty?

    http://www.replicator.org/node/88

    regards


    Reply

    • 3 months ago by arens

      how to use?


      Reply | Hide replys

      • 25 days ago by Andy

        You can use Category.Include(category => category.Products)

        Category is EntityObject
        Category.Products is EntityObject or ObjectSet<EntityObject>


        Reply

    • 25 days ago by Andy

      Nice, but I think there's no way using this one to include

      Category.Include("Products.Owner")

      where property Products is ObjectSet<Product>

      Is there simple way of duing such Include? It could be something like this

      Category.Include(category => category.Products, product => product.Owner)


      Reply

      << [1] >>