Why is Entity Framework navigation property null?

时间秒杀一切 提交于 2019-12-08 11:09:10

问题


I am use code first model with a relationship below

  public class ApplicationUser : IdentityUser
{
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public string UserSchool { get; set; }

    public UserProfileData UserProfileData { get; set; }

    public int? MedicalSpecialtyId { get; set; }
    public virtual MedicalSpecialty MedicalSpecialty { get; set; }

  //  public int? AnalyticsDataId { get; set; }
 //   public ICollection<AnalyticsData> AnalyticsDatas { get; set; }
}

  public class MedicalSpecialty
{
    public int Id { get; set; }
    public string Description { get; set; }

  //  public int ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public ICollection<ProgramDetailData> ProgramDetailDatas { get; set; }
}

And when I try to get a User's associated MedicalSpecialty object it is NULL

 userSpecialtyName = currentUser.MedicalSpecialty.Description;

BUT when I run this code above it the currentUser.MedicalSpecialty is no longer NULL. What happened?? Somehow that LINQ query woke up the object and filled it with data

  var userSpecialtyId = currentUser.MedicalSpecialtyId;
            userSpecialtyName = _medicalSpecialtyRepository.Find
                                    (x => x.Id == userSpecialtyId).FirstOrDefault().Description;

            userSpecialtyName = currentUser.MedicalSpecialty.Description;

来源:https://stackoverflow.com/questions/50217537/why-is-entity-framework-navigation-property-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!