简体   繁体   English

嵌套的Func <T, object> 在通用扩展方法中

[英]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. 随着实现的一些mojo,这很漂亮。 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 . 这构建,并且Intellisense按照我的预期工作,但当然在实际尝试使用它时,它会因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. queryable.Target ,我假设是我试图引用的IQueryable<T> ,似乎不是我的假设,我没有看到我的Intellisense / Quickwatch选项中明显的其他选择。

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? 如何在我的IEntityUnitOfWork q值设置为我想要在以下语句中引用的IQueryable<T>属性?

OK, after more tinkering, it looks like I didn't want the Target property of the function, but rather the Invoke() method: 好吧,经过更多的修补,看起来我不想要函数的Target属性,而是Invoke()方法:

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. ......这完全符合要求。

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

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