Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Using include to join related entity in Entity Framework

I am developing an Asp.net mvc project. I am using EF code first approach to interact with code first approach. But there is one thing I seriously want to know and that is what I do not know about EF yet. What I want to do is I want to join related entities using include without using Join().

I have entities like this

public class Place{
    public ICollection<Contact> Contacts;
}


public class Contact{
    public Place Place;
    public Area Area;
}

public class Area{
   public ICollection<Contact> Contacts; 
}

In above condition I am trying to retrieve places but all related entities are joined using Include.

This is what I am doing

context.Places.Include("Contacts").Include("Area");

It threw error.

enter image description here

But I know I can use join statement to retrieve all. But code will be a little complicated. So is it possible to join using Include in above condition? Is join the only option here?

Upvotes: 0

Views: 369

Answers (2)

Adil Mammadov
Adil Mammadov

Reputation: 8676

Why just not use strongly typed version of Include? You can retrieve Contacts and Areas simply:

context.Places.Include(m => m.Contacts.Select(c => c.Area));

Upvotes: 1

Tom Wuyts
Tom Wuyts

Reputation: 854

What you actually need to do is this:

context.Places.Include("Contacts.Area");

When chaining includes, write them as one include as above.

In your original, it would look for the property Area in the object Places. But it cannot find it there.

Upvotes: 0

Related Questions