Dimich Parkhomchuk
Dimich Parkhomchuk

Reputation: 25

Entity Framework - loading entities by multiple navigation properties in one request

Good afternoon, everyone! I've got a new question: assume that I have the following entity in my database:

public class Entity1
{
public virtual Entity2 Navigation1 {get;set;}
public virtual Entity3 Navigation2 {get; set;}
......
}

And I need is to execute the following query:

SELECT * FROM Entity1 ent1
join Entity2 as ent2 on ent2.Id = ent1.Entity2Id
join Entity3 as ent3 on ent3.Id = ent1.Entity3Id

If I code this way:

context.Entry(ent1).Reference(rep=>rep.Navigation1).Load();
context.Entry(ent1).Reference(rep=>rep.Navigation2).Load();

Entity Framework will execute 2 queries. How am I supposed to rewrite the code so that the framework performs only one call to the database?

Upvotes: 1

Views: 471

Answers (1)

Denis Pitcher
Denis Pitcher

Reputation: 3240

You want to utilize the navigation properties.

For example:

IQueryable<Entity1> query = DBContext.Set<Entity1>()
    .Include(x => x.Navigation1)
    .Include(x => x.Navigation2);

IList<Entity1> mylist = query.ToList();

mylist would then contain your entity with properties set matching your associated entities.

Upvotes: 1

Related Questions