开发者

navigating many-to-many via include in EF4

I have a many to many relationship in EF4 with the following entities:

[Student] - [Class] - [Student_Class]

Moreover i have a [School] entity with a FK on [Student].

If i want to have all the Stud开发者_如何学运维ents of my school i do:

context.School.Include("Student")

but if i want to have the 1rst class of my Students in my school ?

context.School.Include("Student").Include("Student_Class").Where(...

i did not manage to make this thing work... Can you help ? Also is it more intelligent to write a full Linq select? Thanks John


If you want to do a conditional eager load, then you should NOT be using the Include method. For loading your school object containing only the students that belong to the first class You can do a Filtered Projection which returns an Anonymous Type object:

var school = context.School
                    .Where(s => s.SchoolID == 1) // or any other predicate
                    .Select(s => new 
                    {
                        School = s,
                        Students = s.Student.Where(st => st.ClassID == 1)
                    }).ToList();


Another way would be to Leverage Attach Method which returns EntityObject:

var school = context.School.Where(s => s.SchoolID == 1).First()
var sourceQuery = school.Students.CreateSourceQuery()
                                 .Where(st => st.ClassID == 1);
school.Students.Attach(sourceQuery);

For a more detailed discussion about this, you can also check:
Entity Framework: How to query data in a Navigation property table

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜