Mitch
Mitch

Reputation: 2551

LINQ query to return true if associated (related) record exists for each person

I have a People object with a related (associated) table of FavoritePeople. The FavoritePeople object just stores the UserId and PersonId so we know which people are a users favorites.

I'm using Entity Framework 4.2 with Code First and I have mapped all of the fields in People except for IsFavorite which a Boolean and my idea was to set this to true if a related record existed in FavoritePeople.

I'd like to return all the people records with the correct value in the IsFavorite column.

Although I can work out how to do this in SQL, I'm stuck on how to do this in LINQ!

Any suggestions?

Upvotes: 1

Views: 1953

Answers (2)

Jonas Jämtberg
Jonas Jämtberg

Reputation: 571

I dont have enough rep to comment so I'll reply with an answer;

Going with Tyron's solution will give you horrible performance if you select multiple People.

You should either eagerly load the FavoritePeople reference with .Include(x => x.FavoritePeople) when querying for People (warning: chance of huge dataset from db)
OR (preferably) rewrite your query to include IsFavorite:

ctx.Peoples.Select(x => new 
{ 
     x.Name, 
     IsFavorite = x.FavoritePeople.Any()
});

Upvotes: 0

TheRealTy
TheRealTy

Reputation: 2429

IF you have a property for FavoritePeople, you may be able to..

public bool IsFavorite {get{return FavoritePeople.Any();}}

Upvotes: 1

Related Questions