c# - 为什么我在 ApplicationUser 中的自定义对象属性为空?

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-5

我创建了一个名为 Person 的自定义类来存储姓名、地址等。这个类/模型是从其他模型交叉引用的,包括 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;
    }
}

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

        var user = UserManager.FindById(User.Identity.GetUserId());
        var person = user.Person;

我的 Person 类也在 ApplicationDbContext 中定义:

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

    public DbSet<Person> People { get; set; }
}

当我检查 user 时,我可以看到 Entity Framework 填充了该对象,因为我看到了用户 ID、电子邮件地址、密码哈希等所有内容!所有除了 Person 属性!但是,我可以在数据库中看到相应的行不是 null,而是具有 Person 的正确 ID。

我是 ASP.NET/MVC/Entity 框架的新手,我了解到它默认使用延迟加载。这是我正在经历的吗?如果是这样,我如何告诉实体对 Person 属性使用预先加载?如果不是,我做错了什么?

最佳答案

这可能是一个映射问题。 Entity Framework 映射太复杂了,我无法在这里解释,但我会指出问题可能出在哪里。

确保 ApplicationUser 以 Entity Framework 可以理解的方式为 Person 提供外键属性。 Entity Framework 是基于约定的,因此默认情况下它会在您的 ApplicationUser 类中查找 PersonId 属性。如果您不想使用默认名称,您可以在 Context 的 OnModelCreating 上使用流畅的配置来为其指定自定义名称。

我个人认为手动映射您的所有关系始终是个好主意。这是一个例子:

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

更多信息请引用此链接:https://msdn.microsoft.com/en-us/data/jj591620.aspx

关于c# - 为什么我在 ApplicationUser 中的自定义对象属性为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29426031/

相关文章:

c# - 从一个实现 INotifyPropertyChanged 的​​基类继承?

asp.net - IIS 7.5 的 CORS 设置

c# - 任何将 Sendgrid 的解析 API 与 c# ASP.NET MVC 一起使用的人

c# - 在 C# 中的两个应用程序之间共享数据成员

c# - Windows服务与计划任务

c# - 按名称 (ID) C# for ASP.NET 查找文本框

asp.net-mvc - 何时在 MVC4 应用程序中使用 DTO(数据传输对象)?

asp.net-mvc - 将额外数据传递给 EditorTemplate

c# - 如何访问Windows Phone 8.1 中的下载文件夹

asp.net - 在 IIS 上安装后无法使用浏览器浏览 asp.net Web 服务 (.asmx)