我想从输入Include
动态添加params[]
。我怎么能这样做?
这是我的代码
IQueryable<Work> query = this.ObjectContext.Works
.Include("EmployeeSender.Person")
.Include("EmployeeReceiver.Person")
.Include("WorkCode")
.Include("WorkFlowStep.WorkFlowFormState")
.Include("WorkFlow")
.Include("WorkRoot.EmployeeSender.Person")
.Include("WorkParent");
答案 0 :(得分:6)
在循环中,例如:
IQueryable<Work> query = null;
query = this.ObjectContext.Works;
foreach (var param in params)
{
query = query.Include(param);
}
var result = query.ToList();
正如Christian Dietz所提到的那样,你可以将它放在一个扩展方法中,以便它可以重复使用。
答案 1 :(得分:3)
您可以在以下问题中将L-Three的答案与扩展方法结合起来。
Using .Include() when joining a view using Entity Framework
public static IQueryable<T> Include<T>(this IQueryable<T> sequence, params string[] includes) {
var objectQuery = sequence as ObjectQuery<T>;
if (objectQuery != null){
foreach(item in includes){
objectQuery.Include(item);
}
return objectQuery;
}
return sequence;
}
然后你应该能够使用包括:
IQueryable<Work> query = null;
query = this.ObjectContext.Works.Include("Something", "Whatever");
答案 2 :(得分:1)
EF Core无法进行延迟加载。 Refer here
或者,您可以使用预先加载。
阅读此article
以下是我为实现预期加载而创建的扩展方法。
扩展方法:
public static IQueryable<TEntity> IncludeMultiple<TEntity, TProperty>(
this IQueryable<TEntity> source,
List<Expression<Func<TEntity, TProperty>>> navigationPropertyPath) where TEntity : class
{
foreach (var navExpression in navigationPropertyPath)
{
source= source.Include(navExpression);
}
return source.AsQueryable();
}
存储库调用:
public async Task<TEntity> FindOne(ISpecification<TEntity> spec)
{
return await Task.Run(() => Context.Set<TEntity>().AsQueryable().IncludeMultiple(spec.IncludeExpression()).Where(spec.IsSatisfiedBy).FirstOrDefault());
}
用法:
List<object> nestedObjects = new List<object> {new Rules()};
ISpecification<Blog> blogSpec = new BlogSpec(blogId, nestedObjects);
var challenge = await this._blogRepository.FindOne(blogSpec);
依赖关系:
public class BlogSpec : SpecificationBase<Blog>
{
readonly int _blogId;
private readonly List<object> _nestedObjects;
public ChallengeSpec(int blogid, List<object> nestedObjects)
{
this._blogId = blogid;
_nestedObjects = nestedObjects;
}
public override Expression<Func<Challenge, bool>> SpecExpression
{
get { return blogSpec => blogSpec.Id == this._blogId; }
}
public override List<Expression<Func<Blog, object>>> IncludeExpression()
{
List<Expression<Func<Blog, object>>> tobeIncluded = new List<Expression<Func<Blog, object>>>();
if (_nestedObjects != null)
foreach (var nestedObject in _nestedObjects)
{
if (nestedObject is Rules)
{
Expression<Func<Blog, object>> expr = blog => blog.Rules;
tobeIncluded.Add(expr);
}
}
return tobeIncluded;
}
如果有帮助会很高兴。请注意,这不是生产就绪代码。