EF lambda表达式中的左外连接

时间:2012-11-29 04:05:59

标签: c# .net linq entity-framework left-join

我有以下EF查询,它只返回数据库中存在的日期的使用数据列表。

var DailyUsage = context.UsageData.Where(u => u.UserID == CurrentUser.ID && u.Date >= Start && u.Date <= End)
                                  .Select(p => new PerfData
    {
        Date = p.Date,
        Transfers = p.Transfers,
        Exists = p.Exists,
        Duration = p.Duration
    }).ToList();

我希望它返回一个列表,其中包含一个不间断的日期序列,数据点为0表示数据库中不存在的日期,所以我尝试使用以下日期列表进行左外连接,但似乎无法做对了:

public static List<DateTime> GetDateRange(DateTime startingDate, DateTime endingDate)
{
    if (StartingDate > EndingDate)
    {
        return null;
    }
    List<DateTime> rv = new List<DateTime>();
    DateTime tmpDate = startingDate;
    do
    {
        rv.Add(tmpDate);
        tmpDate = tmpDate.AddDays(1);
    }
    while (tmpDate <= endingDate);
    return rv;
}

1 个答案:

答案 0 :(得分:3)

如果我理解正确并且DateTimes列表是联接的外部部分,则可以使用join into子句执行left outer join

var dailyUsages = context.UsageData
     .Where(u => u.UserID == CurrentUser.ID &&
                 u.Date >= start && 
                 u.Date <= end)
     .Select(p => new PerfData()
                  {
                      Date = p.Date,
                      Transfers = p.Transfers,
                      Exists = p.Exists,
                      Duration = p.Duration
                  }).ToList();

var dates = (from date in GetDateRange(start, end)
             join dailyUsage in dailyUsages on date equals dailyUsage.Date into grp
             from item in grp.DefaultIfEmpty(new PerfData()
                                             {
                                                 Date = date,
                                                 Transfers = 0,
                                                 Exists = 0,
                                                 Duration = 0
                                             })
             select item).ToList();