我想通過IQueryable
作爲參數傳遞給一個函數,然後將調用實體框架提供如下執行查詢:如何將IQueryables合併爲一個調用?
public ICollection<MyRowType> RunCommand(IQueryable<MyRowType> query)
{
using (var db = new MyDbContext())
{
var result = db.MyRowType
.Include(r => r.RelatedTableA)
.Include(r => r.RelatedTableB)
.Include(r => r.RelatedTableC)
// How do I make the value in `query` run here?
.ToList();
}
}
我基本上環繞我的數據庫調用此方法返回所有必要的包括但我不想失去通過IQueryable<MyRowType>
進行自定義查詢的靈活性。
這裏是想什麼,我實現一個例子:
public ICollection<MyRowType> SomeOtherMethod(string id, SomeValue value = null, SomeOtherValue otherValue = null)
{
var query = Enumerable.Empty<MyRowType>()
.Where(r => r.Id == di);
if (value != null)
query = query.Where(r => r.PropertyOne == value);
if (otherValue != null)
query = query.Where(r => r.PropertyTwo == otherValue);
return RunCommand(query);
}
答案更新:
我的Yacoub Massad和dasblinkenlight的答案組合成這兩種方法:
public static ICollection<MyRowType> RunCommand(Expression<Func<MyRowType, bool>> condition)
{
return Get(t => t.Where(condition));
}
public static ICollection<MyRowType> RunCommand(Func<IQueryable<MyRowType>, IQueryable<MyRowType>> query)
{
using (var db = new DbContext())
{
var includes = db.MyRowType
.Include(r => r.RelatedTableA)
.Include(r => r.RelatedTableB)
.Include(r => r.RelatedTableC)
var result = query(includes)
.ToList();
return result;
}
}
你能給你想傳遞一個查詢的例子嗎? –