Entity Framework - How to get filtered Master records along with filtered Detail records?
My class relationship: ClassMaster 1----* ClassSessions
My开发者_C百科 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!
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);
In case you loaded all ClassSession objects somewhere in context, you can still do this:
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; }
}
精彩评论