Asp.net mvc 5 在单独文件中使用Fluent API的1:1关系-MVC5,ASP.NET标识

Asp.net mvc 5 在单独文件中使用Fluent API的1:1关系-MVC5,ASP.NET标识,asp.net-mvc-5,asp.net-identity,Asp.net Mvc 5,Asp.net Identity,我正在使用ASP.NETIdentity开发MVC5应用程序。我想在一个单独的文件中使用Fluent API创建1:1关系。该关系应该是User表和UserInfo表之间的关系 用户信息类: public class UserInfo { public int Id { get; set; } public string LastName { get; set; } public string FirstName { get; set; }

我正在使用ASP.NETIdentity开发MVC5应用程序。我想在一个单独的文件中使用Fluent API创建1:1关系。该关系应该是User表和UserInfo表之间的关系

用户信息类:

public class UserInfo
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Address { get; set; }
        public DateTime? BirthDate { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public ApplicationUser User { get; set; }
    }
在IdentityModels.cs中,我添加了以下内容:

public class ApplicationUser : IdentityUser
{
    public virtual UserInfo UserInfo { get; set; }
  //… 
    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserInfoConfigurations());

// If I define relationship like this here, it’s working, 
// but I want it in a separate file.
// modelBuilder.Entity<UserInfo>()
//       .HasRequired<ApplicationUser>(p => p.User);

        base.OnModelCreating(modelBuilder);
    }


public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<UserInfo> UserInfo { get; set; }
}
UserInfoConfigurations.cs,其中我要定义1:1关系:

public class UserInfoConfigurations : EntityTypeConfiguration<UserInfo>
{
    public UserInfoConfigurations()
    {
        ToTable("UserInfo");            
        HasKey(t => t.Id);

        Property(t => t.FirstName).HasColumnType("NVarchar").HasMaxLength(30);
        Property(t => t.LastName).HasColumnType("NVarchar").HasMaxLength(30);
        // and so on for each property

// I want it here. I thought it’s something like this, but it’s not working.
     .HasRequired(t => t.User);
    } 
} 

谢谢。

您希望将定义另存为一个文件的原因是什么?ApplicationDbContext中的默认API和定义关系有什么问题?因为我编辑文章的每个属性都需要应用更多的其他配置,所以如果我将所有配置都保存在IdentityModels.cs中,尤其是当我有更多具有自己配置的表时,这将是一个混乱。这就是为什么我喜欢单独保存它,然后在ApplicationDbContext中调用它。如果我在ApplicationDbContext中为UserInfo实体定义了一个关系,那么我就不能再调用这个单独的文件来应用其他配置了。我的意思是,如果我没有找到其他方法,那么我将把该表的所有配置都放在ApplicationDbContext中,但是我真的认为有一种方法可以像我想要的那样定义这种关系。为什么你说它在UserInfoConfigurations类上不起作用?HasRequiredt=>t.User;至少应该编译。它确实编译,但当我尝试创建一个新用户时,代码中断,因为关系不起作用,它不会创建UserInfo实体的实例。