【问题标题】:Is there any way I can achieve this in Entity Framework? [duplicate]有什么方法可以在实体框架中实现这一点? [复制]
【发布时间】:2021-07-07 08:57:38
【问题描述】:

我正在运行一个 ASP.NET Core Web API 项目,并且我有这个具有自引用关联的模型类:

public class VehicleCategory 
{
    [Key]
    public int Id { get; set; }
    public string description { get; set; }

    [ForeignKey("ParentVehicleCategoryId")]
    public int? ParentVehicleCategoryId { get; set; }
    [JsonIgnore]
    public virtual VehicleCategory ParentVehicleCategory { get; set; }
    public virtual IEnumerable<VehicleCategory> subVehicleCategories { get; set; }
}

我已在 EF 中配置所有内容以检索获取所有数据,并将此配置添加到 startup.cs 文件中以防止循环:

services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

问题是当我尝试从数据库中获取所有数据时,我最终得到了这个 json 结果:

[
  {
    "id": 7,
    "description": "description 1",
    "parentVehicleCategoryId": null,
    "subVehicleCategories": [
      {
        "id": 9,
        "description": "description 2",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      },
      {
       "id": 10,
        "description": "description 3",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      }
    ]
  },
  {
    "id": 9,
    "description": "description 2",
    "parentVehicleCategoryId": 7,
    "subVehicleCategories": null
  },
  {
    "id": 10,
    "description": "description 3",
    "parentVehicleCategoryId": 7,
    "subVehicleCategories": null
  }
]

有没有一种方法可以让我只使用代表孩子的数组来获取这些数据:

[
  {
    "id": 7,
    "description": "description 1",
    "parentVehicleCategoryId": null,
    "subVehicleCategories": [
      {
        "id": 9,
        "description": "description 2",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      },
      {
       "id": 10,
        "description": "description 3",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      }
    ]
  },
 
]

要获取数据,我正在使用此代码:

var test = _raceContext.VehicleCategories
                       .Include(x => x.subVehicleCategories)
                       .ToList();

【问题讨论】:

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


    【解决方案1】:

    如果您只想包含顶级实体及其子实体,则可以使用Where 子句仅获取ParentVehicleCategorynull 的实体:

    var test = _raceContext.VehicleCategories
                           .Where(vc => vc.ParentVehicleCategory == null)
                           .Include(x => x.subVehicleCategories)
                           .ToList();
    

    这样,顶级列表是“无父”实体,但二级实体将出现在您的树中,因为这些实体都是某个父级的子级,并且由于您调用Include 方法。如果你只有两个层次的层次结构,这个方法对你有用,但是如果一个“子”实体也可以是一个“父”,你需要做一些额外的工作。

    【讨论】:

    • 这将仅返回顶级和第一级实体,其余级别将丢失。
    • 是的,我认为我的第一句话就很清楚了。但我编辑了我的最后一段可能会增加一些清晰度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多