Jack
Jack

Reputation: 15872

Model property is always null

For some reason the Owner property is always null, I'm not sure what could be causing this as the rest of the class properties are loading fine. The only difference here is that the properties type is not primitive.

Model Code

#region : Project :
[Table("Project")]
public class Project
{
    ...   
    public UserAccount Owner { get; set; }
    ...
}

Line in the database

ProjectID = 61
CreatedDate = 2013-05-26 17:04:07.480
ProjectName = 'test'
Owner_Username = 'someusername'
UserAccount_Username = 'someusername'

Creation of the Context DbSet

public DbSet<Project> Projects { get; set; }

Attempt to retrieve the owner

Project _Project = _Db.Projects.FirstOrDefault(p => p.ProjectID == projectID);                
UserAccount _Owner = _Project.Owner; //<--- Null

What could be preventing the owner object from being instantiated?

Upvotes: 2

Views: 100

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

If the Owner is coming from a separate table, then the Entity Framework will not load it unless you indicate that you want it to be included in the query results. Try this:

Project _Project = _Db.Projects.Include("Owner").FirstOrDefault(p => p.ProjectID == projectID);                

Upvotes: 2

Related Questions