C
C#2y ago
moritz

❔ one to zero or one relationship EFC

How can I model a 1:cn relationship in Entity Framework Core? E.g. An employee either has a supervisor or not
12 Replies
Tvde1
Tvde12y ago
Relationships - EF Core
How to configure relationships between entity types when using Entity Framework Core
Tvde1
Tvde12y ago
you might just need
class Employee
{
public int Id { get; set; }

public Employee? Manager { get; set; }
}
class Employee
{
public int Id { get; set; }

public Employee? Manager { get; set; }
}
And it will create a FK for you
moritz
moritz2y ago
if i do _db.Employees.Include(e => e.Manager) it filters out employees without managers. how can you avoid that?
Tvde1
Tvde12y ago
it doesn't filter out anything it makes is to when the query runs, it will also fetch the person's managers if you omit the Include, the .Manager will be null for everybody, because EF by default does not load all references if it would always do that, it would make a lot of queries slow when the properties are not used
moritz
moritz2y ago
it uses an inner join in the compiled sql query apparently, that would explain why its filtered for me
Tvde1
Tvde12y ago
that is very odd
moritz
moritz2y ago
only difference is that i have the new-ish #nullable disabled so i dont have the question mark after the type name
Tvde1
Tvde12y ago
I'm pretty sure it does not inner join
Tvde1
Tvde12y ago
linqpad shows a left join
Tvde1
Tvde12y ago
you can output the generated SQL on an IQueryable<T> with .ToQueryString()
moritz
moritz2y ago
now it works correctly, weird. i swear yesterday it didnt
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.