我使用两个类。
public partial class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<IntRole> Roles { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public partial class ApplicationUser : IdentityUser<int, IntUserLogin, IntUserRole, IntUserClaim>
{
public virtual User User { get; set; }
}
我想将这两个类映射到表AspNetUsers。 我配置了此表中的所有字段以使其可选。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().HasOptional(a => a.User).WithMany().HasForeignKey(a => a.Id);
modelBuilder.Entity<ApplicationUser>().HasRequired(a => a.User).WithRequiredDependent(s => s.ApplicationUser);
modelBuilder.Entity<ApplicationUser>().Property(a => a.EmailConfirmed).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.PhoneNumber).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.PhoneNumberConfirmed).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.TwoFactorEnabled).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.LockoutEnabled).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.AccessFailedCount).IsOptional();
modelBuilder.Entity<ApplicationUser>().Property(a => a.UserName).IsOptional();
modelBuilder.Entity<User>().ToTable("AspNetUsers");
}
我进行自动迁移,结果成功。 当我想在控制器中添加由User类定义的单个User时。
context.SpecialUser.Add(new Models.User { FirstName = "Halo", LastName = "Halo2" });
context.SaveChanges();
我收到了以下信息。 遇到无效数据。缺少必需的关系。检查StateEntries以确定约束违规的来源。