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.
public class Employee
{
[Key]
public int EmpId { get; set; }
[Required, MaxLength(100)]
public string EmployeeName { get; set; }
[Required]
public Designation Designation { get; set; }
}
public class Designation
{
[Key]
public int DesigId { get; set; }
[Required, MaxLength(100)]
public string DesignationName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
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.