[英]Nested Func<T, object> in a Generic Extension Method
我有一個如此定義的接口:
public interface IEntityUnitOfWork : IEntityModelUnitOfWork, IDisposable
{
IQueryable<T> IncludeProperties<T>(IQueryable<T> theQueryable, params Func<T, object>[] toInclude)
where T : class, new();
}
...這允許我編寫這樣的代碼:
var foo = MyUnitOfWork.IncludeProperties(
MyUnitOfWork.MyQueryable,
p=>p.MyProperty1,
p=>p.MyProperty2,
...
p=>p.MyPropertyN);
隨着實現的一些mojo,這很漂亮。 但它似乎很尷尬。 我想我應該能寫這個更干凈的,所以我可以使用這種格式:
var foo = MyUnitOfWork.Fetch(
f=>f.MyQueryable,
p=>p.MyProperty1,
p=>p.MyProperty2,
...
p=>p.MyPropertyN);
所以我寫了一個像這樣的擴展方法:
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 ;
}
這構建,並且Intellisense按照我的預期工作,但當然在實際嘗試使用它時,它會因NullReferenceException
而失敗。 queryable.Target
,我假設是我試圖引用的IQueryable<T>
,似乎不是我的假設,我沒有看到我的Intellisense / Quickwatch選項中明顯的其他選擇。
如何在我的IEntityUnitOfWork
q
值設置為我想要在以下語句中引用的IQueryable<T>
屬性?
好吧,經過更多的修補,看起來我不想要函數的Target
屬性,而是Invoke()
方法:
var q = queryable.Invoke(unitOfWork);
經過一些優化后,我看起來像這樣:
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);
}
......這完全符合要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.