为什么ApplicationUser中的自定义对象属性为null?

Luk*_*ngl 2 c# asp.net asp.net-mvc entity-framework asp.net-mvc-5

我创建了一个名为Personstore name,address等的自定义类.这个类/模型与其他模型交叉引用,包括ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public Person Person { 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的一个控制器中,我使用以下代码来获取当前用户登录并获取它的Person对象,如下所示:

        var user = UserManager.FindById(User.Identity.GetUserId());
        var person = user.Person;
Run Code Online (Sandbox Code Playgroud)

我的Person课程也定义在ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("MyContext", throwIfV1Schema: false)
    {
    }

    public DbSet<Person> People { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我检查时user,我可以看到Entity Framework填充了对象,因为我看到了用户ID,电子邮件地址,密码哈希,一切!除了Person财产以外的一切!但是,我可以在数据库中看到相应的行不是null,但具有正确的ID Person.

我是ASP.NET/MVC/Entity框架的新手,我读过它默认使用延迟加载.这是我正在经历的吗?如果是这样,我如何告诉实体在Person物业上使用预先加载?如果没有,我做错了什么?

And*_*ena 5

这可能是一个映射问题.实体框架映射太复杂了我无法在这里解释,但我会指出问题可能出在哪里.

确保ApplicationUser具有PersonEntity Framework可以理解的外键属性.实体框架是基于约定的,因此默认情况下它将PersonId在您的ApplicationUser类中查找属性.如果您不想使用默认名称,可以在Context上使用流畅配置OnModelCreating为其指定自定义名称.

我个人认为手动映射所有关系总是一个好主意.这是一个例子:

public void OnModelCreating(ModelBuilder modelBuilder)
{
    builder.Entity<ApplicationUser>().HasRequired(m => m.Person).HasForeignKey(d => d.Person) 
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此链接:https://msdn.microsoft.com/en-us/data/jj591620.aspx