1

My class relationship: ClassMaster 1----* ClassSessions
My Goal: Return all ClassMasters that have ClassSessions with StartDateTime greater than the current date, along with these ClassSessions (filtered by date).

In T-SQL I'd do this:

select *
   from ClassSession
   join ClassMaster on ClassMaster.ClassId = ClassSession.ClassId
   Where ClassSession.StartDateTime > getdate()

I need to realize the same results in an Entity Framework 4 query. This is what I thought it would work, but does not:

   var classes = ctx.ClassSessions
                 .Include("ClassMasters")
                 .Where(s => s.StartDateTime > DateTime.Now)
                 .Select(s => s.ClassMaster)
                 .ToList();

This give's me all the ClassMasters that have some ClassSession with StartDateTime > current date, but the ClassSessions property comes filled with all ClassSessions, including older than current date. I only want ClassSessions with StartDateTime > current date.

What am I doing wrong?

Thank you very much!

4

1 回答 1

0
var masters = ctx.ClassMasters
         .Where(cm => cm.ClassSessions.Any(cs => cs.StartDateTime > DateTime.Now))
         .Select(cm => new { ClassMaster = cm, ClassSessions = cm.ClassSessions.Where(cs => cs.StartDateTime > DateTime.Now)
         .ToList().Select(e => e.ClassMaster);

如果您在上下文中的某处加载了所有 ClassSession 对象,您仍然可以这样做:

var masters = ctx.ClassMasters
         .Where(cm => cm.ClassSessions.Any(cs => cs.StartDateTime > DateTime.Now))
         .Select(cm => new ClassMasterWithSessionModel{ ClassMaster = cm, ClassSessions = cm.ClassSessions.Where(cs => cs.StartDateTime > DateTime.Now)
         .ToList();

public class ClassMasterWithSessionModel {
    ClassMaster ClassMaste { get; set; }
    IEnumerable<ClassSession> ClassSessions { get; set; }
}
于 2011-02-18T16:05:36.343 回答