使用表AspNetUsers进行EF表拆分

时间:2018-01-29 10:58:38

标签: asp.net asp.net-mvc entity-framework

我使用两个类。

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以确定约束违规的来源。

我应该定义什么关系? InnerException的结果。 enter image description here

0 个答案:

没有答案
相关问题