在单独的文件中使用Fluent API的1:1关系 - MVC5,ASP.NET Identity

时间:2015-02-21 11:57:23

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

我正在使用ASP.NET Identity进行MVC5应用程序。我想在单独的文件中使用Fluent API创建1:1关系。关系应该在表User和UserInfo之间。

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);
    } 
} 

谢谢。

0 个答案:

没有答案