I have a project with classes in a project that I am building in a Code First style. The problem is simple. The objects in question are a User and a userType.
public class User
{
[Key]
public int id { get; set; }
[DisplayName("User Name")]
[Required(ErrorMessage = "User Name is required.")]
public string userName { get; set; }
[DataType(DataType.Password)]
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required.")]
public string userPassword { get; set; }
[DisplayName("First Name")]
public string first_Name { get; set; }
[DisplayName("Last Name")]
public string last_Name { get; set; }
[DisplayName("Email")]
public string email { get; set; }
[DisplayName("Zip")]
public string Zip { get; set; }
[DisplayName("Address")]
public Address address { get; set; }
[DisplayName("Birthdate")]
public DateTime dateOfBirth { get; set; }
[DisplayName("Home phone")]
public string homePhone { get; set; }
[DisplayName("Cell phone")]
public string cellPhone { get; set; }
[DisplayName("Remember me")]
public bool persistCookie { get; set; }
public UserType userType { get; set; }
public int status { get; set; }
}
AND
public class UserType
{
[Key]
public int id { get; set; }
public string typeName { get; set; }
}
I generate a User like this:
userType = (from ret in db.UserTypes where ret.typeName.Equals("Contractor") select ret).FirstOrDefault();
user.userType = userType;
user.status = 1;
db.Users.Add(user);
db.SaveChanges();
The database schema seems to support the foreign key to the UserTypes table.
Everything works well on the add and in the database I see a user record with the appropriate userType_id.
The problem comes when I retrieve the user later on. My User.userType is always null. This has me really confused. If the userType key is in the Users table for the record, why do I not get a userType object as part of my User when I get that user using a standard LINQ query like:
User user = (from ret in db.Users where ret.userName.Equals(userIn.userName) && ret.userPassword.Equals(userIn.userPassword) select ret).FirstOrDefault();
I get the User but user.userType is always null.
What am I missing here?
Should I be building a different LINQ query?
Shouldn’t the userType object be automatically included in the User object?
I think the Code First programming style is an excellent methodology but this problem has me baffled.
Thanks for any help!
You need to tell EF to eager load the navigational property
userTypeby usingIncludemethod.Or make the
userTypeproperty virtual so that EF will lazy load it.