Alas you forgot to show us your classes. If you followed the entity framework code first conventions, you'll have classes similar to the following:
class Department
{
public int Id {get; set;}
...
// Every department has zero or more Students (one-to-many)
public virtual ICollection<Student> Students {get; set;}
}
class Student
{
public int Id {get; set;}
...
// every Student belongs to exactly one department, using foreign key
public int DepartmentId {get; set;}
public virtual Department Department {get; set;}
}
And your DbContext
class UniversityContext : DbContext
{
public DbSet<Department> Departments {get; set;}
public DbSet<Student> Students {get; set;}
}
This is all that Entity Framework needs to know to identify your tables, the columns in the tables and the one-to-many relation between the tables
Note: in entity framework the columns in a table are represented by
non-virtual properties. The virtual properties represent the relations
between the tables
The virtual properties make your life much easier, because you don't have to do (group)joins anymore. Just use the virtual collections, entity framework will translate this into the proper joins.
I want to show a list with DepartmentName for each StudentName,
var result = universityDbContext.Students
.Where(student => ...) // only if you don't want all Students
.Select(student => new
{
// select only the properties you plan to use
Id = student.Id,
StudentName = student.Name,
DepartmentName = student.Department.Name,
});
Because you used student.Department
, entity framework knows that a SQL join
is needed.
If you want a flat SQL join, start with the 'many' side, and use the
virtual property to the 'one' side. If you want a grouped join, start
with the 'one' side and use the virtual ICollection to the 'many'
side.
You wanted a flat join, but if you wanted Departments with their Students
you would have done something like:
var result = myDbContext.Departments
.Where(department => ...) // if you don't want all departments
.Select(department => new
{
// select only the properties you plan to use
Id = department.Id,
Name = department.Name,
StudentsWithHighGrades = department.Students
.Where(student => student.Grade >= ...)
.Select(student => new
{
Id = student.Id,
Name = student.Name,
Grade = student.Grade,
...
})
.ToList();
});