I have a class that looks like this :
public partial class Defect
{
public int DefectID { get; set; }
public string Title { get; set; }
public virtual DefectStatus DefectStatus { get; set; }
public virtual Developer Developer { get; set; }
public virtual Project Project { get; set; }
}
When I call this :
var defect = db.Defects.Find(id);
How can I make it fill Project with the relational data from the Project table?
Currently I am doing the following defect.Project to populate defect.Project
var defect = db.Defects.Find(id);
defect.Project = db.Projects.Find(defect.ProjectID);
But I want to know if there is a better way to accomplish the same thing?
If you are still inside the db context when you ask for the Project, then (because you have marked the property Virtual), Project will be lazy loaded. If you are outside the db context, then you need to load it (as you are doing) while in the context.
However, you can eager load the Project entity by not using the Virtual keyword or by using Include in your query:
db.Defects.Include("Project").Where(d => d.DefectId.Equals(id));This looks like the best reference for loading entities.