我正在尝试为急切加载导航属性添加多个linq表达式。我找到了很多博客/教程,S.O。涉及该主题的问题,但是在实施时似乎都不起作用。最奇怪的是,如果我在查询上实现包含它确实有效,但这当然会失败传递大量表达式的目的。让我举个例子。 COntroller repo call:
// GET api/application/5
public HttpResponseMessage Get(int id)
{
var _repo = new BaseRepository();
//_repo.Find<Application>(a => a.Id == id).Result
var app = Task.Run(async () => { return await _repo.Find<Application>(id,
e => e.Users);
}
).Result;
if (app != null)
{
return Request.CreateResponse(HttpStatusCode.OK, app);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"The application could not be located.");
}
}
Repo方法包含参数的不同方式:
public async Task<T> Find<T>(int id, params Expression<Func<T, object>>[] includes)
where T: Application
{
IQueryable<T> query = _db.Set<T>();
//for (var i = 0; i < includes.Length; i++)
// query = query.Include(includes[i]);
//foreach (var include in includes)
//{
// query = query.Include<T, object>(include);
//}
//if (includes.Any())
//{
// query = includes.Aggregate<Expression<Func<T, object>>, IQueryable<T>>
// (_db.Set<T>(), (current, expression) => current.Include(expression));
//return await query.Where(e => e.Id == id).AsNoTracking().SingleOrDefaultAsync();
//}
return await query.Where(e => e.Id == id).SingleOrDefaultAsync();
}
不会抛出错误的唯一方法:
return await query.Include(includes[0]).Where(e => e.Id == id).SingleOrDefaultAsync();
错误:
{调用目标已抛出异常}
内部例外: {在程序集中复制类型名称}
我真的在这个问题上遇到了障碍,我理解这应该只适用于任何这些循环实现。但是在执行查询时会抛出错误。
先谢谢你们!