在实体框架中自联接Lambda查询

时间:2015-11-10 09:16:12

标签: c# entity-framework lambda

我的代码是

    var model = dt.FishEventScheduleVaccination
            .Join(
                dt.FishEventSchedule,
                vaccination => vaccination.ScheduleId,
                schedule => schedule.ScheduleId,
                (vaccination, schedule) => new { vaccination, schedule }
            )
            .Select(q=>new {
                q.vaccination,
                q.schedule
            })
            .Where(w=>w.schedule.Start>DateTime.Now).ToList();
        var rtn=new List<FishEventScheduleVaccination>();
        foreach (var m in model) {
            var item = m.vaccination;
            item.FishEventSchedule = m.schedule;
            rtn.Add(item);
        }

我只想做lambda查询,而不是foreach。我能怎么做?有可能吗?

2 个答案:

答案 0 :(得分:1)

from r in Entities.tbl join q in Entities.tbl on r.Id equals q.Id2 select new
{
    Id = r.Column + " " + r.Column, Data = q.Column + " " + q.Column 
};

我认为这应该可以解决您的查询

OR

你也可以尝试这样的事情:

db.DTOPageSets.Join(db.DTOPageSets
                    .AsEnumerable(), a => a.ContentPageID, b => b.CategoryID, (a, b) => a);

答案 1 :(得分:1)

请改为尝试:

dt.FishEventScheduleVaccination
    .Join(dt.FishEventSchedule,
          vaccination => vaccination.ScheduleId,
          schedule => schedule.ScheduleId,
          (vaccination, schedule) => new { vaccination, schedule })
    .Where(w => w.schedule.Start > DateTime.Now)
    .AsEnumerable()
    .Select(q => { q.vaccination.FishEventSchedule = q.schedule; return q.vaccination; })
    .ToList();