【问题标题】:Web API with Entity Framework inheritance具有实体框架继承的 Web API
【发布时间】:2018-09-12 14:29:19
【问题描述】:

假设我有以下实体:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    您将不得不更改返回类型

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

    【讨论】:

    • 我只想要“Bs”集合中的 ID
    【解决方案2】:

    我用这个方法解决了这个问题:

    [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;
    }
    

    【讨论】:

      【解决方案3】:

      要从类型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();
      }
      

      【讨论】:

      • 我只想要“Bs”集合中的 ID
      • 谢谢 Marcus,我有两个问题 - 我无法从 users 集合中 SelectMany(u => u.Bs) 因为 Bs 只是 UserA 的一个属性 - 我需要结果为 IEnumerable 类型,我用一个例子更新了这个问题。
      猜你喜欢
      • 1970-01-01
      • 2011-05-19
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多