如何动态传递 .Include & .Select

How to dynamically pass .Include & .Select

我正在使用 EF-6 开发 asp.net mvc5 网络应用程序。我正在尝试动态传递 .Include & .Select 如下:-

          var query = context.SecurityRoles.AsQueryable();
          foreach (var include in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
          {
              query = query.Include(include);
          }
          return await query
              .SingleOrDefaultAsync(a2 => a2.SecurityRoleID == id);
      }

我将调用如下:-

var securityrole = await uniteofwork.SecurityRoleRepository
                .FindSecurityRole(id.Value, "SecurityRoleModulePermissions.Select(a2=>a2.Module),SecurityRoleModulePermissions.Select(a2=>a2.PermissionLevel)),Staffs");

但是我收到以下异常:-

A specified Include path is not valid. The EntityType 'SkillManagementModel.SecurityRoleModulePermission' does not declare a navigation property with the name 'Select(a2=>a2'

您可以像这样动态地包含您的导航属性:

public async Task<SecurityRole> FindSecurityRole(Expression<Func<SecurityRole, bool>> predicate, params Expression<Func<SecurityRole, object>>[] includeProperties)
{
    var query = context.SecurityRoles.AsQueryable();
    if (includeProperties != null)
        query = includeProperties.Aggregate(query, (current, include) => current.Include(include));

    return await query.SingleOrDefaultAsync(predicate);
}

var securityrole = await uniteofwork.SecurityRoleRepository.FindSecurityRole
    (sr => sr.Id == id.Value, sr => sr.Module, sr =>sr.PermissionLevel)