0

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.

1
  • You don't need to in initialize userList.You context returns that list. Commented Mar 28, 2014 at 13:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm, what you do is Eager, not Lazy loading.
Lazy loading is making additional queries to load related entities
And Lazy loading is no more available as soon as you dispose your context (as you do with your using clause)
Thanks for the correction. I've changed my answer to state that its Eager loading, not Lazy Loading :)
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.