1

我有两张桌子(一对多)。MeterReadings(0..1) and MeterReadingDetails(*)

我想加入这些表格并按日期分组。日期字段在 MeterReadings 中,其他字段在 MeterReadingDetails 中。

我使用了这段代码:

林克

public static IEnumerable<MeterReadingsForChart> GetCustomerTotal(int CustomerId, int MeterTypeId, DateTime StartDate, DateTime EndDate, MeterReadingsTimeIntervals DateRangeType)
{
    var customerReadings = from m in entity.MeterReadings
        join n in entity.MeterReadingDetails on m.sno equals n.ReadingId
        where m.Meters.CustomerId == CustomerId && m.ReadDate >= StartDate && m.ReadDate <= EndDate && m.Meters.TypeId == MeterTypeId
        group n by new { date = new DateTime(m.ReadDate.Value.Year, m.ReadDate.Value.Month, 1) } into g
        select new MeterReadingsForChart
        {
             ReadDate = g.Key.date,
             Value = g.Sum(x => x.Value),
             Name = g.FirstOrDefault().MeterReadingTypes.TypeName
         };

    return customerReadings;
}

MeterReadinsForChart.cs

public class MeterReadingsForChart
{
    public DateTime ReadDate { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
}

但我得到了这个错误:

LINQ to Entities 仅支持无参数构造函数和初始化程序

如何加入、分组和求和?

4

1 回答 1

2

尝试以下操作:

var customerReadings = (from m in entity.MeterReadings
    join n in entity.MeterReadingDetails on m.sno equals n.ReadingId
    where m.Meters.CustomerId == CustomerId && m.ReadDate >= StartDate && m.ReadDate <= EndDate && m.Meters.TypeId == MeterTypeId
    group n by new { Year = m.ReadDate.Value.Year, Month = m.ReadDate.Value.Month} into g
    select new
    {
         Key = g.Key,
         Value = g.Sum(x => x.Value),
         Name = g.FirstOrDefault().MeterReadingTypes.TypeName
     }).AsEnumerable()
       .Select(anon => new MeterReadingsForChart
       {
         ReadDate = new DateTime(anon.Key.Year, anon.Key.Month, 1),
         Value = anon.Value,
         Name = anon.Name
       });

无。它丑陋,但实体框架不允许您创建 DateTime (作为一个没有无参数构造函数的结构)。所以在这种情况下,我们想要大部分来自 db 的结果,然后作为这个流,我们在内存中构造日期。

于 2012-11-09T10:10:35.787 回答