Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Func<T, object> in a Generic Extension Method

I have an interface defined like so:

public interface IEntityUnitOfWork : IEntityModelUnitOfWork, IDisposable
{
    IQueryable<T> IncludeProperties<T>(IQueryable<T> theQueryable, params Func<T, object>[] toInclude)
        where T : class, new();
}

...which allows me to write code like this:

var foo = MyUnitOfWork.IncludeProperties(
    MyUnitOfWork.MyQueryable,
    p=>p.MyProperty1,
    p=>p.MyProperty2,
    ...
    p=>p.MyPropertyN);

With some mojo on the implementation, this works pretty swimmingly. But it seems awkward. I think I should be able to write this cleaner, so I can use this sort of format:

var foo = MyUnitOfWork.Fetch(
    f=>f.MyQueryable,
    p=>p.MyProperty1,
    p=>p.MyProperty2,
    ...
    p=>p.MyPropertyN);

So I wrote an extension method like this:

public static IQueryable<T> Fetch<T>(
    this IEntityUnitOfWork unitOfWork,
    Func<IEntityUnitOfWork, IQueryable<T>> queryable,
    params Func<T, object>[] toInclude) where T:class, new()
{
    var q = queryable.Target as IQueryable<T>;
    foreach (var p in toInclude)
    {
        q = unitOfWork.IncludeProperties(q, new[] { p });
    }
    return q ;
}

This builds, and the Intellisense works as I would expect it to, but of course when actually trying to use it, it fails with a NullReferenceException. The queryable.Target, which I assumed would be the IQueryable<T> that I was trying to reference, does not appear to be what I assumed, and I don't see an obvious other choice from my Intellisense/ Quickwatch options.

How do I set that q value to be the IQueryable<T> property off my IEntityUnitOfWork that I want to reference in the following statements?


1 Answers

OK, after more tinkering, it looks like I didn't want the Target property of the function, but rather the Invoke() method:

var q = queryable.Invoke(unitOfWork);

after a bit of optimization, I made it look like this:

public static IQueryable<T> Fetch<T>(
    this IEntityUnitOfWork unitOfWork,
    Func<IEntityUnitOfWork, IQueryable<T>> queryable,
    params Func<T, object>[] toInclude) where T : class, new()
{
    var q = queryable.Invoke(unitOfWork);
    return unitOfWork.IncludeProperties(q, toInclude);
}

...and this works exactly as desired.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!