. 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

2

1 Answer

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest