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:
- We first use
Select(d => d.c)to pull out the actualCarsentity from each item in the grouped data. 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).- We then apply your
HasPremium == trueandStatus == "Sold"filters specifically to the SUVs. - Finally,
Sum()calculates the total value of those qualifying vehicles.
If you still run into errors, double-check:
- That
CarsSUVis properly derived from your baseCarsclass - That your EF inheritance configuration is correctly set up (e.g., a discriminator column in the database that identifies SUVs)
- That
HasPremiumis a property exclusive toCarsSUV(and not defined on the baseCarsclass)
内容的提问来源于stack exchange,提问作者JCricket
相关产品推荐
相关产品推荐

