如何动态传递.Include& 。选择

时间:2015-02-08 02:18:21

标签: asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6

我正在使用EF-6开发一个asp.net mvc5 Web应用程序。我想动态传递.Include& 。选择如下: -

          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");

但我得到以下例外: -

  

指定的包含路径无效。 EntityType   'SkillManagementModel.SecurityRoleModulePermission'未声明   导航属性,名称为“选择”(a2 => a2'

1 个答案:

答案 0 :(得分:1)

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

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)