Daniel Santos Daniel Santos - 4 months ago 12
C# Question

Will Entity Framework perform n+1 queries for 1:1 reference related tables?

If I have this POCO class.

class MainEntity
public int id {get;set;}
public string name {get;set;}
public virtual Related myRelated {get;set;}

related to this class

class Related
public int id {get;set;}
public string name {get;set;}

The entities are related on a 1:1 basis.

Will the query
perform N+1 queries to the DB due to lazy loading, or, once it's 1:1 reference related, will perform just 1 query?


When you do your ToList, it will just retrieve the list of all your MainEntity objects with one query. If you have any related entity linked they will not be loaded at all.

Then, once you navigate to the myMain.Related property, lazy loading will trigger and will create a query to load the values for that related reference object.

Now, if you'd like to directly load all data in the reference in one query it's also possible. You can use the .Include extension method to do this. In your example, it would look something like this:

db.MainEntity.Include(m => m.Related).ToList()

You should also check this page which goes into the details on how you can do lazy / eager loading and what it means in terms of SQL.