C
C#3y 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
Tvde13y ago
Relationships - EF Core
How to configure relationships between entity types when using Entity Framework Core
Tvde1
Tvde13y 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
moritzOP3y ago
if i do _db.Employees.Include(e => e.Manager) it filters out employees without managers. how can you avoid that?
Tvde1
Tvde13y 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
moritzOP3y ago
it uses an inner join in the compiled sql query apparently, that would explain why its filtered for me
Tvde1
Tvde13y ago
that is very odd
moritz
moritzOP3y ago
only difference is that i have the new-ish #nullable disabled so i dont have the question mark after the type name
Tvde1
Tvde13y ago
I'm pretty sure it does not inner join
Tvde1
Tvde13y ago
linqpad shows a left join
Tvde1
Tvde13y ago
you can output the generated SQL on an IQueryable<T> with .ToQueryString()
moritz
moritzOP3y ago
now it works correctly, weird. i swear yesterday it didnt
Accord
Accord3y 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.
Want results from more Discord servers?
Add your server