Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Entity Framework Code First Navigation Property is null - solution

5.00/5 (1 vote)
19 Mar 2013CPOL1 min read 30.9K  
A simple possible solution to Entity Framework Code First Navigation Property/Related Records not being loaded automatically

Introduction 

If you are using Code First Approach to Entity Framework and you use Visual Studio Snippets support ("class" snippet)  to construct your entities POCO classes, you might sometimes notice that your Navigation properties are not loaded at run time even if you mark the navigation properties as virtual. A simple workaround might solve your issue. Just add the "public" modifier to your class definition, which Visual Studio by default does not add.

Background

I am a great fan of Visual Studio snippets. When I was first using Code First development, I bumped into the strange behavior of my application where my navigation properties would not load even if everything looked right at the database side (relationships, foreign keys, etc.)  I toggled lazy loading, etc., without help. Finally, it was just leaving out an access modifier "public" causing these issues.

Using the code

In the following code, the classes are prefixed with public, which might be missing in the default VS snippet. Without this modifier, if you try to access the related record (in this case either Designation or Employees), you will find that it is null. Even if you enable lazy loading and mark the navigation properties as virtual, it will not work. In that case, add "public" keyword as shown in the following example.

C#
//employees table
public class Employee
{
    [Key]
    public int EmpId { get; set; }

    [Required, MaxLength(100)]
    public string EmployeeName { get; set; }

    [Required]
    public Designation Designation { get; set; }

}

//Designations table.
public class Designation
{
    [Key]
    public int DesigId { get; set; }

    [Required, MaxLength(100)]
    public string DesignationName { get; set; }

    
    public virtual ICollection<Employee> Employees { get; set; }  

}

//example of accessing the code from a different class:
MyDBContext context = new MyDBContext();
var desig = context.Employees.FirstOrDefault().Designation.DesignationName;

Points of Interest

It is interesting that adding/leaving out an access modifier like "public" or "virtual" can have a great impact on how the entire application is going to work and can lead to a developer losing his valuable time for no apparent reason.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)