2016-08-07 22 views
0

我有3个嵌套模型:ApplicationUser(来自实体框架),City和State。 应用程序用户具有城市作为外键,城市具有作为外键的状态。 当我查询一个用户时,我得到一个包含City在内的所有属性的用户作为相关模型,但是当我查找城市时,相关模型State为null,所有其他属性都可以。任何线索?嵌套实体模型查询问题

这是StateModels

public class StateModels 
    { 
     public int Id { get; set; } 
     public string State { get; set; } 
     public string Abbreviation { get; set; } 
    } 

这是CityModels

public class CityModels 
    { 
     public int Id { get; set; } 
     public string City { get; set; } 
     public int ZipCode { get; set; } 
     public virtual StateModels State { get; set; } 
    } 

这是ApplicationUser

public class ApplicationUser : IdentityUser 
    { 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string CompanyName { get; set; } 
     public string Address1 { get; set; } 
     public string Address2 { get; set; } 
     public virtual CityModels City { get; set; } 
     public string CompanyPhone { get; set; } 
     public string CompanyFax { get; set; } 
     public bool Validated { get; set; } 
     public bool Staff { get; set; } 
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
     { 
      // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
      var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
      // Add custom user claims here 
      return userIdentity; 
     } 
    } 

这是我试图去的状态对象

ApplicationUser applicationUser = db.Users.Find(idUser); 
var city = applicationUser.City; //object city is ok 
var state = city.State; // this field is null, all others attributes are ok 

在db中,所有的城市寄存器都有状态ID参考

回答

0

试试这个。 db.Users.Find(idUser).Include(u => u.City).Include(u => u.City.State)并确保所有外键都已正确设置。