嵌套实体模型查询问题

时间:2016-08-07 18:14:11

标签: asp.net asp.net-mvc asp.net-mvc-5

我有3个嵌套模型:ApplicationUser(来自实体框架),城市和州。 ApplicationUser将城市作为外键,城市作为外键使用。 当我查询用户时,我得到一个具有其所有属性的用户,包括City作为相关模型,但是当我查找到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引用

1 个答案:

答案 0 :(得分:0)

试试这个。 db.Users.Find(idUser).Include(u =&gt; u.City).Include(u =&gt; u.City.State)并确保正确设置了所有外键。