'.Net Entity Framework load many to many IDs only

I use EF, and have an association many to many table.

I implemented creating explicetely the association table, and referencing the entity

Public class ModelContainer
{
   [Required]
   Guid Id {get; set;}
  ...
}

Public class ModelElement
{
  [Required]
  Guid Id {get; set;}
 ...
}

Class Container_Element
{
   [Required]
   Guid ContainerId {get; set;}
   [Required]
   Guid ElementId {get; set;}
   ModelContainer Container {get; set;}
   ModelElement Element {get; set;}
}

(And declared keys and index in the database context)

It does work fine.

But for a specific query, I'd like to load the associations, but only the IDs, I don't want to consume too much more memory with the entities.

Is there a way to load from my association table, but only the ContainerId/ElementId ?

Thank you



Solution 1:[1]

By default, reading the Container_Element from a DbSet in the DbContext will only load the IDs into memory if you do not explicitly eager load the related entities. As you have them declared there, unless you are using EF Core 5/6 /w proxy-less lazy loading the navigation properties would be #null. However, if the DbContext is already tracking the related entities in memory then those references will be set, though that doesn't increase memory usage as EF associates references, it doesn't return multiple copies of the same entity.

If you declare the navigation properties as virtual or use proxy-less lazy loading then these still would not be populated until accessed unless the DbContext was already tracking the entities.

Generally when loading large sets of data from entity graphs where you don't need all of the data/relationships, it is a good investment to get familiar with projection using Select. EF can build queries that just return the specific columns from entities and their related entities without the overhead of eager-loading all columns from all applicable tables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve Py