首页 > 解决方案 > EF Core 5.0.2 - 组加入计数

问题描述

我知道已经有一些关于此的主题,但似乎没有一个可以帮助或解决我的问题。我正在尝试执行具有一对多关系的查询并简单地提供一个计数。我试过用几种方法编写这个查询,但似乎无法让它工作。我正在使用 EF Core 5.0.2。

示例: 我以前用过这个,它确实有效。自从我更改为 NET5 以来,现在似乎没有。

var query = (from p in _db.Devices
join variant in _db.DeviceVariations.DefaultIfEmpty() on p.Id equals variant.DeviceID
into variants
select new DeviceBasicView.Model
{
    DeviceID = p.Id,
    DeviceName = p.DeviceName,
    DeviceType = p.DeviceTypeIdentifier,
    Manufacturer = p.DeviceManufacturer,
    Status = p.Status,
    VariantCount = variants.Count()
}).ToList();

我也尝试了以下方法,没有将整个数据集拉入内存,我不知道如何让它工作。任何帮助,将不胜感激。即使这意味着将我的实体类更改为具有 ICollections?(我对 EF Core 有点陌生,通常使用 EF6)

var test = (from p in _db.DeviceVariations.Include("Device")
group p by new { p.Device } into deviceGrouped
select new
{
    Device = deviceGrouped.Select(s => s.Device),
    Variants = deviceGrouped.Count()
}).ToList();


var query2 = (from p in _db.Devices
join s in _db.DeviceVariations on p.Id equals s.DeviceID 
into variants
from s in variants.DefaultIfEmpty()
group s by new { s.DeviceID } into deviceGrouped
select new
{
    Device = deviceGrouped.Select(s => s.Device),
    Variants = deviceGrouped.Count()
}).ToList();

标签: entity-framework-coreleft-joinentityone-to-many

解决方案


求助于在这里发帖,我刚刚设法解决了它。我将以下内容添加到我的设备实体中(我的变体实体中已经有 FK 引用)并修改了我的查询,如下所示。猜猜我只需要完全映射关系。

设备实体

 public List<DeviceVariationEntity> Variants { get; set; }

变体实体

  [ForeignKey("DeviceID")]
  public DeviceEntity Device { get; set; }

工作查询

var query = (from p in _db.Devices.Include("Variants")                                         
select new DeviceBasicView.Model
{
   DeviceID = p.Id,
   DeviceName = p.DeviceName,
   DeviceType = p.DeviceTypeIdentifier,
   Manufacturer = p.DeviceManufacturer,
   Status = p.Status,
   VariantCount = p.Variants.Count()
 }).ToList();

推荐阅读