0

I am learning EF and LINQ to EF. We are using LINQ Methods and not LINQ Expressions.

I am trying to do a very simple query from my 2 entities.

NavigationGroup is a one to many relation to NavigationGroupLocation. The Navigation Property in NavigationGroup is called "NavigationGroupLocations"

In my mind this code should work:

 List<NavigationGroup> groups = db.DataModel.NavigationGroups.Where(g => g.NavigationGroupLocations.Location == 1).ToList();

Location is an int in my NavigationGroupLocation entity.

Can someone explain why this doesn't work and what the proper way to filter by a navigation property? I have seen many example in the expression syntax and can't seem to relate it to the method syntax.

I am using C# 4 & EF 4.

Thanks for the help!

EDIT

I see that since my Navigation Property is a collection I can't get to an individual property. So I am trying this code:

 .Where(g => g.NavigationGroupLocations.Any(l => l.Location == 1));

When I try to run it I get this error:

 Cannot implicitly convert type 'System.Linq.IQueryable<ME.Data.ECom.NavigationGroup>' to 'System.Data.Objects.ObjectSet<ME.Data.ECom.NavigationGroup>'. An explicit conversion exists (are you missing a cast?)

What should I be doing?

Jared
  • 2,443
  • 8
  • 26
  • 40

2 Answers2

0

You need to do a Join. NavigationGroupLocations is a list of items, so you cannot access .Location property in the where clause.

Salvador Sarpi
  • 981
  • 1
  • 8
  • 19
  • How do you do a Join in linq method syntax? Can you look at my edit and see if I am headed in the right direction by using .Any()? – Jared Apr 13 '12 at 18:50
0

It looks like this works:

 var query = db.DataModel.NavigationGroups.Where(g => g.NavigationGroupLocations.Any(l => l.Location == selectedLocation));

It is not working when used as a conditional statement.

 var query = db.DataModel.NavigationGroups;
 if (selectedLocation > 0)
 {
    query = query.Where(g => g.NavigationGroupLocations.Any(l => l.Location == selectedLocation));
 }

That is when I get the error.

Jared
  • 2,443
  • 8
  • 26
  • 40