user1640256
user1640256

Reputation: 1719

Correct query using Entity Framework

I have two tables "Users" and "UserType". There is a relationship between these tables on "userTypeID" column. This column is primary key in the "UserType" table and foreign key in the "User" table. I also have a property in "User" class like follows:

public virtual UserType usertype{ get; set; }

I am querying "User" table like follows:

List<MyApp.Entity.Models.User> userList = new List<User>();
using (var DBContext = new UserDBContext())
{
userList  = DBContext.User.Where(x => x.IsActive == true).OrderBy(i => i.userName).ToList();
return userList;
}

When I am debugging the code, userList.usertype is null. I need to have the UserType in the userList. What am I doing wrong? I am new to Entity Framework.

Upvotes: 0

Views: 77

Answers (2)

CallumVass
CallumVass

Reputation: 11458

Include at the top of your class:

using System.Data.Entity

Then modify your query like so:

userList  = DBContext.User
                .Include(u => u.usertype)
                .Where(x => x.IsActive)
                .OrderBy(i => i.userName)
                .ToList();

This is called Eager Loading. You can read more about it here: Loading Related Entities

Upvotes: 1

Loetn
Loetn

Reputation: 4040

You have to explicitly include your usertype.

userList  = DBContext.User
.Include("usertype")
.Where(x => x.IsActive == true).OrderBy(i => i.userName).ToList();

Or with lambda: Add using System.Data.Entity;

userList  = DBContext.User
.Include(x => x.usertype)
.Where(x => x.IsActive == true).OrderBy(i => i.userName).ToList();

Upvotes: 1

Related Questions