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

Linq to Entities继承场景下SUV溢价已售车辆价值求和问题

Hey there! Let's work through getting that SUV value sum working in your LINQ query. The issue with your initial attempt is that you're trying to use OfType<CarsSUV>() directly on the grouped data (g), but g contains the anonymous type you created earlier (with c and sales properties) — not the Cars entities themselves.

Here's how to fix it, integrated right into your existing query:

var statsModel = (
    from c in db.Cars
    join s in db.Salesman on c.SalesmanId equals s.ID into sales
    select new { c, sales } into data
    group data by new { data.c.ModelName, data.c.Year } into g
    select new MyData
    {
        CarYear = g.Key.Year,
        SomeCount = g.Count(d => d.c.Status == "Sold"),
        // 其他统计项保持不变...
        HelpWithSUVSum = g
            // 先提取分组里的每个Car实体
            .Select(d => d.c)
            // 筛选出属于SUV类型的车辆
            .OfType<CarsSUV>()
            // 应用你的过滤条件
            .Where(suv => suv.HasPremium && suv.Status == "Sold")
            // 对符合条件的SUV价值求和
            .Sum(suv => suv.CarValue)
    }
).ToList();

Quick breakdown of why this works:

  1. We first use Select(d => d.c) to pull out the actual Cars entity from each item in the grouped data.
  2. OfType<CarsSUV>() filters those entities down to only the SUV subclass (this relies on your inheritance mapping being set up correctly in EF, whether you're using TPH, TPT, or TPC).
  3. We then apply your HasPremium == true and Status == "Sold" filters specifically to the SUVs.
  4. Finally, Sum() calculates the total value of those qualifying vehicles.

If you still run into errors, double-check:

  • That CarsSUV is properly derived from your base Cars class
  • That your EF inheritance configuration is correctly set up (e.g., a discriminator column in the database that identifies SUVs)
  • That HasPremium is a property exclusive to CarsSUV (and not defined on the base Cars class)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:54:38