score:2

Accepted answer

You probably need to enable eager loading for the "OwnedItems" navigation property in the query: https://docs.microsoft.com/en-us/ef/core/querying/related-data#eager-loading

Please post your full linq query if I should give an example.

UPDATE 1

Seems like subqueries have N+1 problems in EF Core and it will maybe be fixed in version 3.

Reference: https://github.com/aspnet/EntityFrameworkCore/issues/10001

UPDATE 2

If you don't need to fully materialize "Items" you should be able to do something like this where you create an anoymous object instead which should "trick" EF into what you want:

from item in Items
select new
{
   Owned = OwnedItems.Any(own => own.UserId == userId && own.ItemId == item.Id),
   Item = new { Id = item.Id, Name = item.Name }
}

Reference: https://github.com/aspnet/EntityFrameworkCore/issues/11186

score:0

You need to tell EF to load the related data, in this case the OwnedItems table.

One way to go about this is to Include the related table. If there's a foreign key that links tables it could be easily done like this:

var dataWithRelatedData = db_context.Items.Include(x => x.OwnedItems).Select ...

Another way to avoid a high number of round trips to the database is to load both datasets in separate queries and then merge them in memory. So you would first make a query to Items then with the data returned another query to OwnedItems and lastly merge them into a single list of objects. This would do just 2 calls to the database, therefore improving performance.


Related Articles