EntityFramework Code First插入语句与FOREIGN KEY约束冲突

时间:2017-01-19 16:04:49

标签: c# entity-framework asp.net-core-mvc code-first

我已经阅读了涉及代码第一个外键约束错误的每一个问题,并与一些人谈过它,我仍然完全不理解错误。我不明白为什么我在尝试处理各种应用程序中的外键时经常看到这一点。人们试图解释问题,我的眼睛茫然。

我在Person模型中有这个:

[Required(ErrorMessage = "Role required.")]
[Display(Name = "Role")]
[ForeignKey("roles")]
public string RoleId { get; set; }

public virtual IdentityRole roles { get; set; }

当新用户注册时,我在AccountController中执行此操作:

string roleid = user.Roles.FirstOrDefault().RoleId;
NewUserToolContext ctx = new NewUserToolContext();
Person person = new Person { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, RoleId = roleid };
ctx.people.Add(person);
ctx.SaveChanges();

为什么每次我尝试使用外键时都会遇到同样的错误?使用外键是不是很好?我已经调试并检查并验证在创建新的“Person”时正确的ID正在传递给model属性。

这是完整的人物模型:

public class Person
    {
        [Key]
        public int PersonId { get; set; }

        [Required(ErrorMessage = "First name required.")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last name required.")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Email required.")]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Role required.")]
        [Display(Name = "Role")]
        [ForeignKey("roles")]
        public string RoleId { get; set; }

        public virtual IdentityRole roles { get; set; }
    }

错误讯息:

  

INSERT语句与FOREIGN KEY约束“FK_dbo.Person_dbo.IdentityRole_RoleId”冲突。冲突发生在数据库“NEWUSERTOOL_7c54952102864024ab864e4bab34f694”,表“dbo.IdentityRole”,列“Id”中。   声明已经终止。

有关详细信息,请参阅我的应用程序的其余部分:

public class NewUserToolContext : DbContext
{
    public DbSet<Location> locations { get; set; }
    public DbSet<Country> countries { get; set; }
    public DbSet<Department> departments { get; set; }
    public DbSet<NewUser> newusers { get; set; }
    public DbSet<Person> people { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }
}

0 个答案:

没有答案