Search code examples
c#postgresqlentity-frameworkasp.net-corenpgsql

How to use where in relation with EntityFramework?


I have two models that are related. Cars and announcements. Announcement and car ha one-to-one relationship.

How can I include a where in the relation?

updated: the name of the property is announcement not announcements and it is not a collection.

this.context.Cars.Include(a => a.announcement); // stuck here, I want to find the
                                                // announcements that are active. 

Solution

  • For a Where() on the Car:

    this.context.Cars.Include(c => c.announcements).Where(c => c.Value == value);
    

    Note, I've change your 'a' to a 'c' on the Include() because it represents a car, not an announcement.

    For a Where() on the Announcement:

    this.context.Cars.Where(c => c.announcements.Value == value);
    

    Note, there is no need to Include() announcements in order to look at it in the Where(). You only need Include() if you're going to read announcements data in the programme once the query is executed.