具有实体框架继承的Web API

时间:2018-09-11 18:16:45

标签: entity-framework asp.net-core-webapi

假设我具有以下实体:

abstract class User
{
    string Id 
    string Name 
}

class UserA : User
{
    List<UserB> Bs
}

class UserB : User
{
    string UserAId
    [ForeignKey("UserAId"), JsonIgnore]
    UserA UserA
}

我想将所有这些加载到一个查询中,并且仅获取集合的ID。例如,如果返回

[HttpGet]
public IEnumerable<Usuario> Get()
{
   return _context.Users.ToList();
}

响应包括来自“ Bs”集合的所有数据

[
    {
        "id": "0",
        "name": "User A",
        "Bs": [
            {
                "id": "1",   
                "name" : ....  
                "aId": ....
            },
            {
                "id": "2",      
                "name" : .... 
                "aId": ....
            }
        ]
    },
    {
        "aId": "0",
        "id": "1",
        "name": "User B 1"
    },
    {
        "aId": "0",
        "id": "2",
        "name": "User B 2"
    }
]

如何在没有额外属性的情况下获取收藏夹?

[
    {
        "id": "0",
        "name": "User A",
        "Bs": [
            {
                "id": "1"
            },
            {
                "id": "2"
            }
        ]
    },
    {
        "aId": "0",
        "id": "1",
        "name": "User B 1"
    },
    {
        "aId": "0",
        "id": "2",
        "name": "User B 2"
    }
]

并从“ Bs”集合中返回不包含“ aId”和“ name”的json

3 个答案:

答案 0 :(得分:0)

要从UserA的Bs集合类型返回ID,您需要根据类型过滤出值,然后在Bs集合上使用SelectMany

[HttpGet]
public IEnumerable<int> Get()
{
   return _context.Where(e => (e is UserA))
                  .Select(u => (UserA)u)
                  .SelectMany(b => b.Bs)
                  .ToList();
}

答案 1 :(得分:0)

我认为您可以使用select语句来投影ID,例如:

_context.Users.Select(user => user.id)

您将不得不更改退货类型

参考: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/method-based-query-syntax-examples-projection

答案 2 :(得分:0)

我通过这种方法解决了这个问题:

[HttpGet]
public IEnumerable<dynamic> Get()
{
    IEnumerable<dynamic> res = _context.Users.OfType<UserA>()
        .Select(u => new {Id = u.Id, Name = u.Name, Users =  u.Users.Select(ui => new  { Id = ui.Id }) })
        .ToArray();

    res = res.Concat<dynamic>(_context.Users.OfType<UserB>());

    return res;
}