2016-08-07 14 views
0

Ich habe 3 verschachtelte Modelle: ApplicationUser (von Entität Framework), Stadt und Staat. ApplicationUser hat Stadt als Fremdschlüssel und Stadt hat einen Status als Fremdschlüssel. Wenn ich einen Benutzer abfrage, erhalte ich einen Benutzer mit allen Attributen einschließlich Stadt als verwandtes Modell, aber wenn ich in die Stadt suche, ist das zugehörige Modell State gleich null, alle anderen Attribute sind in Ordnung. Irgendeine Ahnung?Verschachtelte Entitätsmodelle Abfrage Problem

Dies ist StateModels

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

Dies ist 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; } 
    } 

Und das ist 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; 
     } 
    } 

Dies ist, wie ich versuche, auf den Zustand Objekt zu erhalten

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 

In der Datenbank haben alle Stadtregister die ID

Antwort

0

Versuchen Sie dies. db.Users.Find (idUser) .Include (u => u.City) .Include (u => u.City.State) und stellen Sie sicher, dass Sie alle Fremdschlüssel ordnungsgemäß festgelegt haben.