entity-framework-core - 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();
解决方案
求助于在这里发帖,我刚刚设法解决了它。我将以下内容添加到我的设备实体中(我的变体实体中已经有 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();
推荐阅读
- python - 在 matplotlib 的 hexbin 图中应用插值的过程是什么?
- testing - 使用 Mockito 提供 @InjectMoks 对象的所有依赖项,而 @Mock 无法提供
- python - 在两个数据集之间使用 KDTree 查找最近的邻居
- c - 从 C 中的名称文件中读取字符串时出现问题
- ionic-framework - 如何在 Ionic 5 中使用 cordova-plugin-admob-free
- python - 我的 StringsProperty 代码有问题
- android - 使用 Kotlin 进行改造 2
- typescript - 将布尔构造函数转换为类型保护
- javascript - 访问共享目录时具有身份验证的 fs
- python - 为什么我在 keras 中的自定义指标失败了?