简体   繁体   English

实体框架根导航属性为null,但已填充后代导航属性

[英]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. 根模型上的导航属性始终返回null,而在类似定义的同一模型上的辅助关系可以正确加载。 I'm trying to find out why. 我正试图找出原因。

Using EF6 Code First, eager loading, I have models/navigation properties structured like this: 首先使用EF6代码,急于加载,我具有如下结构的模型/导航属性:

  • ProjectUser 专案使用者
    • Project (always null) 专案(永远为null)
    • User (loads fine) 用户(加载正常)
    • Groups (loads fine) 组(加载正常)
      • Clients 客户群
        • Project (populated correctly - should always be same as ProjectUser.Project) 项目(正确填充-应始终与ProjectUser.Project相同)

My ProjectUser.Project is always null but interestingly the ProjectUser.Groups.Clients.Project is populated correctly. 我的ProjectUser.Project始终为null,但有趣的是ProjectUser.Groups.Clients.Project的填充正确。 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() . 为了进一步使事情变得混乱,我居然能拿到项目,如果在上面的映射更改加载WithOptional()WithMany() However this doesn't make sense to me... So my question is: 但这对我来说没有意义...所以我的问题是:

Why is ProjectUser.Project not loading when using WithOptional ? 为什么在使用WithOptional时未加载WithOptional

WithMany means that your entity might have many of the navigation property as it's called 1-to-many. WithMany意味着您的实体可能具有许多导航属性,因为它称为一对多。

WithOptional means that your entity might have one of the navigation property. WithOptional表示您的实体可能具有导航属性之一。 A one-to-one relationship. 一对一的关系。

Take a look at this post . 看一下这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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