EF Navigational Property RRS feed

  • Question

  • Assuming that Project and Employee are DB entities,
    If I created Employee with null project,
    Is it possible to navigate property to list of Projects > Employees

    E.g. List of Project value would be 

    (Employees WITHOUT project id)

    ProjectId = Null, 

    Employees = (list of employees with Null Project Id)

    (Employees WITH project id)

    ProjectId = 1, 

    Employees = (list of employees with Project Id)

            public class Project
                public virtual int ProjectId { get; set; }
                public virtual ICollection<Employee> Employees { get; set; }
            public class Employee
                public virtual int EmployeeId
                public virtual Project Project { get; set; }

    Thanks for your help.


    • Edited by J0hnPM Thursday, January 26, 2017 1:20 PM
    • Moved by CoolDadTx Thursday, January 26, 2017 2:52 PM EF related
    Thursday, January 26, 2017 1:18 PM

All replies

  • In order for your lazy loading to work you'd need to declare an int ProjectId on the Employee type. Then you'd either want to use a configuration or ForeignKey attribute on the Project property to link it to the ProjectId. Without that EF won't be able to figure out how to load the navigation property.

    Depending upon how you define ProjectId in Employee determines whether it can be nullable or not. If ProjectId is an int then it cannot be null. Trying to save such an object to the DB will result in a 0 being saved which, assuming your DB is properly constrainted, will fail with a constraint error. If an employee does not have to be part of a project then create ProjectId as int? instead.

    When you load the Employee, if ProjectId is set then you can reference the Project property to have it lazy loaded (or use Include to automatically load it). Since EF caches data it loads in the context, if you then dereference the Employees you'll get the list of employees in the project. However if Project is not set then you'll get a null reference exception as the property won't be set.

    Going the other way, Project.Employees will trigger a query for all employee's with the ProjectId set. Since you're querying for employee's associated with the project, each employee's Project property will be set to the same object you're enumerating. This is assuming of course you've configured the navigation properties properly using attributes or a configuration.

    Michael Taylor

    Thursday, January 26, 2017 2:51 PM