51

I'm trying to get data from a LocalDb into my MVC Controller. I tried this:

UsersContext db = new UsersContext();
var users = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId)
                           .Include(u => u.LastName).ToList();

It returns this error:

A specified Include path is not valid. The EntityType 'ChatProj.Models.UserProfile' does not declare a navigation property with the name 'LastName'.

Here is a picture of my localDb and model.

Any idea why it's not working?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
JazzMaster
  • 717
  • 1
  • 8
  • 13
  • I would rather suggest you go through this post https://stackoverflow.com/questions/3356541/entity-framework-linq-query-include-multiple-children-entities – MSI Abu Zafar Newton Jan 07 '19 at 11:42

5 Answers5

48

Navigation property should be of entity type of collection of related entities. Including some navigation property means joining your current entity with some related entity or entities. That allows eager loading of data from several tables in single query. LastName is not a navigation property - it is simple field, and it will be loaded by default, you don't need to include it:

UsersContext db = new UsersContext();
var users = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId)
                           .ToList();

This query will be translated into something like

SELECT UserId, UserName, LastName, FirstName 
FROM UserProfiles
WHERE UserId = @value
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
25

Include is only for navigation properties, and LastName is a scalar property, so you don't need Include at all.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
21

Even though this is not quite related to the question, since Google brings you here, I thought it might be helpful to notice that a likely possibility is that you are using IEnumerable for your collection. Instead you should be using ICollection, see more here: https://stackoverflow.com/a/32997694/550975

This seems to be a problem in EF6 and perhaps earlier versions only... no longer a problem to use either in EF Core.

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
8

If you want to retrieve only the LastName, use

Select(m => m.LastName)

so

 var users = db.UserProfiles
                .Where(u => u.UserId == WebSecurity.CurrentUserId)
                .Select(u => u.LastName)//not Include
                .ToList();

LastName is just a string (Scalar property) in your model, not a Navigation property (relation with another entity)

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
-2

In my case I solved it as the following

the code with the error :

LabResults = db.LAB_RESULTS.Where(o => o.ORDER_ID == id)
.Include(p => p.LabTests).ToList()

then I removed .Include :

LabResults = db.LAB_RESULTS.Where(o => o.ORDER_ID == id).ToList()
Ziad Adnan
  • 710
  • 5
  • 18