A simple entity framework DbContext:
class SchoolDbContext : DbContext
{
public DbSet<Teacher> Teachers {get; set;}
public DbSet<Student> Students {get; set;}
}
Requirement Give me the number of Teachers and the number of Students.
Or, a little bit more challenging: "Give me the names of all Teachers and give me the birthdays of all Students"
Normally it would take two queries to do this. According to the following answers it is possible to do this using SQL in one query:
Answers are like:
SELECT id, startdate, enddate , '-' AS point_id
FROM sarcshiftcentertable
UNION
SELECT id, startdate, enddate, point_id
FROM sarcshiftpointtable
But is it possible to do something similar using LINQ in one query?
The answers point me in the direction of Queryable.Union. However, this function expects for both collections the same input type.
So I should select something in common before the union,
which in this case is object
var result = dbContext.Teachers.Select(teacher => teacher.Name).Cast<object>()
.Union(dbContext.Students.Select(student => student.BirthDay).Cast<object>())
// TODO select?
Now every DateTime in the sequence is a Students birthday. Every string is a Teachers name.
Another possibility is to select a new class:
var result = dbContext.Teachers.Select(teacher => new
{
TeacherName = teacher.Name,
StudentBirthDay = null,
})
.Union(dbContext.Students.Select(student => new
{
TeacherName = null,
StudentBirthDay = student.BirthDay,
}))
// TODO: select?
By now, I can detect whether an Item is a TeacherName, or a StudentBirthDay by checking whether the other property equals null.
But how to continue? How do I get one object like:
new
{
TeacherNames = ...
StudentBirthdays = ...
}
or
new
{
TeacherCount = ...
StudentCount = ...
}