Mohit
Mohit

Reputation: 922

How to do following in Entity Framework 4.1 using Linq

Following is the data model

Assume the above given data model, how to execute following query in EF 4.1

Select 
   students.firstname
   ,students.lastname
   ,classes.classname
   ,IsNull(studentsclasses.id,0) Attending 
from students
cross join classes 
left outer join studentsclasses on studentsclasses.classid = classes.classid 
            and studentsclasses.studentid = students.studentid
where students.studentid = 5

following is my attempt

from s in Students
from c in Classes
select new {
              StudentFirstName = s.Firstname,
              StudentLastName = s.Lastname,
              ClassName = c.Classname
           }

Upvotes: 0

Views: 340

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160892

In Entity Framework the relationship between students and classes should be represented by a navigation property classes in each student Entity that contains all the classes the student is related to. Using this you can do:

var student = Students.FirstOrDefault( s = > s.studentid == 5);
if(student!=null)
{
  var studentClasses = student.classes.Select( c => new
  {
     StudentFirstName = student.Firstname,
     StudentLastName = student.Lastname,
     ClassName= c.Classname     
  });
  //..
}

Upvotes: 3

Related Questions