efcore - 具有导航属性的投影

时间:2017-02-20 07:03:51

标签: c# entity-framework asp.net-core entity-framework-core

从IdentityRole(ApplicationRole)表中获取角色时,我得到以下输出:

[
  {
    "description": "developer role",
    "tenantId": "426b22f1-8baf-41e2-bce6-53e5c6b45974",
    "createdAt": "2017-02-07T11:56:46",
    "modifiedAt": null,
    "users": [],
    "claims": [
      {
        "id": 1,
        "roleId": "59961dcc-6eb6-4509-9355-cca9f61199f3",
        "claimType": "http://schemas.microsoft.com/identity/claims/permission",
        "claimValue": "user:read"
      },
      {
        "id": 2,
        "roleId": "59961dcc-6eb6-4509-9355-cca9f61199f3",
        "claimType": "http://schemas.microsoft.com/identity/claims/permission",
        "claimValue": "user:delete"
      }
    ],
    "id": "59961dcc-6eb6-4509-9355-cca9f61199f3",
    "name": "developer426b22f1-8baf-41e2-bce6-53e5c6b45974",
    "normalizedName": "DEVELOPER426B22F1-8BAF-41E2-BCE6-53E5C6B45974",
    "concurrencyStamp": "4fca1eb6-7ff2-45f9-99d9-2e1a2f85c562"
  }
]

我需要的输出是:

[
  {
    "name": "developer426b22f1-8baf-41e2-bce6-53e5c6b45974",
    "description": "developer role",
    "claims": ["user:read","user:delete"],
    "id": "59961dcc-6eb6-4509-9355-cca9f61199f3",
    "createdAt": "0001-01-01T00:00:00",
    "modifiedAt": null
  }
]

所以,我尝试使用Dto,它的属性在Select()中传递:

public class ApplicationRoleDto : BaseDto<string>
{
    public string Name { get; set; }
    public string Description { get; set; }
    public List<string> Claims { get; set; }

    public static Expression<Func<ApplicationRole, ApplicationRoleDto>> SelectProperties = (role) => new ApplicationRoleDto
    {
        Id = role.Id,
        Name = role.Name,
        Description = role.Description,
        Claims = GetClaimsList(role.Claims),
        CreatedAt = role.CreatedAt,
        ModifiedAt = role.ModifiedAt

    };

    private static List<string> GetClaimsList(ICollection<IdentityRoleClaim<string>> roleClaims)
    {
        var claims = new List<string>();
        foreach (var roleClaim in roleClaims)
        {
            claims.Add(roleClaim.ClaimValue);
        }
        return claims;
    }
}

当我使用Select()投影

GetQueryable<TEntity>(null, orderBy, includeProperties, skip, limit).Select(selectProperties).ToListAsync();

我收到以下错误:

System.InvalidOperationException: The type of navigation property 'Claims' on the entity type 'IdentityRole<string, IdentityUserRole<string>, Identi
tyRoleClaim<string>>' is 'ICollection<IdentityRoleClaim<string>>' for which it was not possible to create a concrete instance. Either initialize the prope
rty before use, add a public parameterless constructor to the type, or use a type which can be assigned a HashSet<> or List<>.

0 个答案:

没有答案