Note: since you have use the plural form for the announcements
property, I deduced it's a collection. My answer is based on this assumption. Btw., the rule is to use PascalCase for properties.
Include always includes all the related records. You have to make the test afterwards:
IEnumerable<Announcement> activeAnnouncements = context.Cars
.Include(c => c.announcements)
.SelectMany(c => c.announcements)
.Where(a => a.IsActive);
Note that SelectMany
flattens nested sequences. Here, it produces a sequence of all announcements in all the cars.
If you had a one-to-many relationship and needed the cars together with the active announcements, you could combine the two in a ValueTuple:
IEnumerable<(Car c, Announcement a)> carsAndActiveAnnouncements = context.Cars
.Include(c => c.announcements)
.SelectMany(c => c.announcements, (c, a) => (c, a)) // 1st (c, a) are lambda parameters,
// 2nd creates tuple.
.Where(ca => ca.a.IsActive);
Get all the cars with active announcements, but including all the announcements (in a one-to-one relationship, this is always a single active announcement):
IEnumerable<Car> carsHavingActiveAnnouncements = context.Cars
.Include(c => c.announcements)
.Where(c => c.announcements.Any(a => a.IsActive));
And finally, you can add this property to the Car
class (expression bodied syntax):
public IEnumerable<Announcement> ActiveAnnouncements =>
announcements.Where(a => a.IsActive);
Same as (full syntax):
public IEnumerable<Announcement> ActiveAnnouncements
{
get {
return announcements.Where(a => a.IsActive);
}
}
It lets you retrieve the active announcements easily at any time. The result is accurate even after edits.
But since, in this case, you have a one-to-one relationship, this does not help much.
Update:
Since, according to your update, announcement
is not a collection and since you want to select the cars having an active announcement, here is my new solution:
IEnumerable<Car> carsHavingAnActiveAnnouncement = context.Cars
.Include(c => c.announcement)
.Where(c => c.announcement.IsActive);
Note that the Include
is not required for the Where
clause to work, as it will be translated to SQL and does not rely on an object reference. But it is of course legitimate, if you want the announcements to be loaded.