1

I have following query in my code:

var query3 = (from b in context.SystemDetails.Include("UserHousing").Include("UserInfo") where (b.UserHousing.UserInfo.FullName.StartsWith("Far")) select b).ToList();

Why does it give error that systemDeail do not have navigation property "UserInfo" .. it should not matter as UserHousing Have that Navigation property...

Sana.91
  • 1,999
  • 4
  • 33
  • 52

2 Answers2

3

You should specify the correct path to UserInfo:

context.SystemDetails.Include("UserHousing.UserInfo")

Or

context.SystemDetails.Include(x => x.UserHousing.UserInfo)
haim770
  • 48,394
  • 7
  • 105
  • 133
1

Your sequence of Include(..) methods is executed against main object being retrieved from context - SystemDetails, and, of course, it doesn't have UserInfo in it.

Paths are all-inclusive. Having both includes replaced with single

Include("UserHousing.UserInfo")

will do the trick. Have a look at documentation for Include(string path) method.

PS. What version of EF are you using? While updating to EF5 I've found following IQueryable extension useful:

DbExtensions.Include<T, TProperty> Method (IQueryable<T>,Expression<Func<T, TProperty>>)

http://msdn.microsoft.com/en-us/library/gg671236%28v=vs.103%29.aspx

See the remarks sections, I believe you are dealing with the following scenario:

  • To include a reference and then a reference one level down: query.Include(e => e.Level1Reference.Level2Reference).

you should end up with something like this in your query:

from b in context.SystemDetails
.Include(detail => detail.UserHousing.UserInfo) ...
Andrew
  • 3,648
  • 1
  • 15
  • 29
  • Version is 6 for EF. I do not prefer using lambda expressions as they seem a bit complex. I achieved same using normal query method. .. Is it necessary to use lambda expressions? – Sana.91 Apr 09 '14 at 08:42
  • 1
    On one hand it's a matter of personal style and taste, on the other it's the maintainability - lambda expression in our case has a typed reference to you entity and it's child property. In case you change something in your model(i.e. UserInfo get's renamed as UserData) - you'll immediately get a compilation error upon first build, where as using string implementation of Include will result in runtime error when you first hit your query. If this code area was not covered with unit tests and it's use case is rather complex, you may simply miss that and deliver to end user with a bug. – Andrew Apr 09 '14 at 09:05