Aleksei Chepovoi
Aleksei Chepovoi

Reputation: 3955

How to access child entity's property in a where clause of linq expression?

I've already asked similar question but it was not very precise, so I will do it again.

Suppose I have a model where one entity includes other entity. Is there any way to access a property of child entity withing a linq query? Here is the example:

string category = "something";

IEnumerable<string> Items = _itemsRepository.GetItems()
                .Where(i => i.Product.Category == category)
                .OrderBy(i => i.ItemId);

In a clause "Where" I want to access child entity's property "Category", (this chunk of code doesn't work). Table "Items" contains foreign key "ProductId" of table "Products".
So here I want to select items which product's category equals "something". How can it be done?

Thank You in advance!

Upvotes: 0

Views: 1336

Answers (3)

Chad
Chad

Reputation: 1562

IEnumerable<Item> Items = _itemsRepository.GetItems()
                .Where(i => category == null || 
                           (i.Product != null && 
                            i.Product.Category == category))
                .OrderBy(i => i.ItemId);

Upvotes: 1

Roger Johansson
Roger Johansson

Reputation: 23214

You are missing a select clause

    IEnumerable<string> Items = _itemsRepository.GetItems()
            .Where(i => i.Product.Category == category)
            .OrderBy(i => i.ItemId)
            .Select(i => i.Name); //<- or whatever string property you expect to get out

Otherwise, you should not have IEnumerable<string> but rather IEnumerable<Item> or what your entity is called.

Upvotes: 0

Ben Tidman
Ben Tidman

Reputation: 2139

As others suggested in their comments providing more info about the error will help us answer your question.

Are you getting a null reference exception?

If so, make sure you are including your child entity/navigation property in the linq statement or query that is being executed in the method _itemsRepository.GetItems().

Entity framework won't load your related objects unless you tell it to. I recommend that you eagerly load your property using the .Include() method. You need to do this as part of whatever query you are executing inside of GetItems(). You can also use lazy loading to get access to your sub properties. Here is an article that explains it some.

http://msdn.microsoft.com/en-us/magazine/hh205756.aspx

Hope that helps.

Upvotes: 1

Related Questions