简体   繁体   中英

Entity Framework root navigation property null but descendent navigation property populated

A navigation property on a root model always returns null while a secondary relationship on the same model that is defined similarly loads correctly. I'm trying to find out why.

Using EF6 Code First, eager loading, I have models/navigation properties structured like this:

  • ProjectUser
    • Project (always null)
    • User (loads fine)
    • Groups (loads fine)
      • Clients
        • Project (populated correctly - should always be same as ProjectUser.Project)

My ProjectUser.Project is always null but interestingly the ProjectUser.Groups.Clients.Project is populated correctly. My project is mapped like so:

HasRequired(pu => pu.Project)
    .WithOptional()
    .Map(m => m.MapKey("ProjectId"));

To further make things confusing I am actually able to get the Project to load if in the above mapping I change WithOptional() to be WithMany() . However this doesn't make sense to me... So my question is:

Why is ProjectUser.Project not loading when using WithOptional ?

WithMany means that your entity might have many of the navigation property as it's called 1-to-many.

WithOptional means that your entity might have one of the navigation property. A one-to-one relationship.

Take a look at this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM