1

I have 2 entities in my db context:

Employee
EmployeeHolidayEntitlement

I think it's a fairly normal one-one relationship - but Employee can exist without EmployeeHolidayEntitlement, but EmployeeHolidayEntitlement cannot exist without Employee

Employee is mapped to a view in my database
EmployeeHolidayEntitlement is a table

My classes are:

EmployeeHolidayEntitlement

[Table("tblEmployeeHolidayEntitlement")]
public class EmployeeHolidayEntitlement
{
    [Key]
    public int EmployeeNumber { get; set; }

    public virtual Employee Employee { get; set; }

    public decimal StandardEntitlement { get; set; }

    //.....omitted for brevity
}

Employee

[Table("vEmployee")] //note v - it's a view
public class Employee
{
    [Key]
    public int EmployeeNumber { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

When building my context, I do:
(not sure if this is correct!)

modelBuilder.Entity<EmployeeHolidayEntitlement>()
  .HasRequired(w => w.Employee)
  .WithOptional();

When querying, if possible, I would like one EmployeeEntitlement record for each Employee (weather it exists in tblEmployeeHolidayEntitlement or not) -

My query currently looks like this:

from
    userEntitlement in db.ADUserHolidayEntitlement
 join
    adUser in db.ADUsers
    on
    userEntitlment.EmployeeNumber equals adUser.EmployeeNumber
select userEntitlement

But this is (i think) doing a LEFT join - It's only returning the 2 entities that have an entry in tblEmployeeHolidayEntitlement

I would imagine the resultant SQL needs to look something like:

SELECT 
employee.EmployeeNumber, 
employeeHol.* 

FROM tblEmployeeHolidayEntitlement employeeHol

RIGHT JOIN vEmployee employee
ON 
employeeHol.EmployeeNumber = employee.EmployeeNumber

Is this even possible?

2 Answers 2

5

Your code is doing an inner join. I believe you're asking to retrieve all employees, and an EmployeeHolidayEntitlement for each employee (if it exists).

To perform a left join, use a query similar to this:

from adUser in db.ADUsers
join userEntitlement in db.ADUserHolidayEntitlement on
    adUser.EmployeeNumber equals userEntitlment.EmployeeNumber into g
from userEntitlement in g.DefaultIfEmpty()
select new 
{
    adUser, 
    userEntitlement // Will be null of no entitlement exists
}
1

Its doing an inner join just like you asked it to.

You do not need an explicit join at all.

You need something like:

from user in db.....
select new{user,user.Entitlement};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.