You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 6中C# LINQ三表关联查询:计算总价并映射DTO字段

EF Core 6 实现对应SQL的LINQ查询及DTO映射

首先定义用于承载查询结果的DTO类(可根据需求添加更多字段):

public class CityPriceDto
{
    public decimal TotalPrice { get; set; }
    public decimal PricePerSqM { get; set; }
    // 这里可以添加其他需要映射的字段,比如CityId、CityName等
}

对应SQL逻辑的LINQ查询代码:

var queryResult = await _dbContext.Cities
    // 过滤目标城市
    .Where(city => city.CityId == 1)
    // 关联CityExtras表
    .Join(_dbContext.CityExtras,
        city => city.CityId,
        cityExtra => cityExtra.CityId,
        (city, cityExtra) => new { City = city, CityExtra = cityExtra })
    // 关联Extras表
    .Join(_dbContext.Extras,
        combined => combined.CityExtra.ExtrasId,
        extra => extra.ExtrasId,
        (combined, extra) => new { combined.City, Extra = extra })
    // 按PricePerSqM分组
    .GroupBy(joined => joined.City.PricePerSqM)
    // 映射到DTO并计算总价
    .Select(group => new CityPriceDto
    {
        PricePerSqM = group.Key,
        TotalPrice = group.Sum(item => item.Extra.ExtraPrice) + (group.Key * 10)
        // 如需映射其他字段,直接从group或item中取值赋值即可
    })
    .ToListAsync();

关键逻辑说明:

  • 两次Join完全对应SQL中的表关联关系,确保数据关联逻辑一致
  • GroupBy与SQL的group by PricePerSqM等价,分组键为PricePerSqM
  • Select中直接实现总价计算逻辑,和SQL的sum(c.ExtraPrice) + (a.PricePerSqM*10)完全匹配,同时完成DTO字段映射

内容的提问来源于stack exchange,提问作者Hareem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:35:21