将实体添加到身份模型

Adding entity to Identity model

我目前遇到一个错误,我理解这个错误,但我不知道哪里出错了

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUsers_dbo.CompanyDetails_userCompanyID". The conflict occurred in database "PXWHITESPIDERDEV", table "dbo.CompanyDetails", column 'companyID'.

在您创建 MVC 应用程序时自动生成的 IdentityModel 中

public class ApplicationUser : IdentityUser
{

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }


    public int userCompanyID { get; set; }

    [ForeignKey("userCompanyID")]
    public CompanyDetails company { get; set; }
}

这是我要创建的实体

 public class CompanyDetails
 {
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int companyID { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 1)]
    [Display(Name = "Company Name")]
    public string CompanyName { get; set; }
 }

并且在 RegisterViewModel 中 class

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public CompanyDetails company { get; set; }
}

之前 companyID 在 ApplicationUser class 和 CompanyDetails class 中是相同的,因为它们具有相同的变量名称。我认为这是问题所在,因此更改了 ApplicationUser class 中的变量名称,直到我尝试再次更新数据库并发现情况并非如此。

当您添加新的companyID 属性时,Entity Framework显然需要在dbo.AspNetUsers table中添加一个新列来表示它。由于此列之前不存在且不可为空,因此需要在列中为现有记录设置一些默认值。对于 int 类型,默认值为 0。但是,0 未接受 table 作为外键,因此当 Entity Framework 尝试附加该约束时,它失败了。

解决问题的最简单方法是 1) 从 dbo.AspNetUsers 中删除所有现有行或 2) 添加列并在附加外键之前手动将值更新为实际的 CompanyDetails ID约束。

或者,您也可以将 companyId 设置为可为 null 的 int,这将允许 Entity Framework 在添加列时在数据库中将其清零。可以将外键约束添加到具有空值的列,因此一切都应该可以正常工作。但是,这意味着这种关系现在是可选的。如果每个用户都应该总是有一个相关的CompanyDetails,那么找到另一种方法来解决这个问题。