【问题标题】:Adding entity to Identity model将实体添加到身份模型
【发布时间】:2015-05-14 18:09:33
【问题描述】:

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

ALTER TABLE 语句与 FOREIGN KEY 约束“FK_dbo.AspNetUsers_dbo.CompanyDetails_userCompanyID”冲突。冲突发生在数据库“PXWHITESPIDERDEV”、表“dbo.CompanyDetails”、列“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 类中

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

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

【问题讨论】:

    标签: c# entity-framework asp.net-mvc-5 asp.net-identity


    【解决方案1】:

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

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

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

    【讨论】:

    • nullable int 部分再重要不过了:nullable FK 列上的 SQL 关系是完全有效的,并且在某些情况下非常重要。例如,考虑具有ClosedBy 字段的SupportTicket 表;在SupportTicket 关闭之前,您不希望设置ClosedBy 字段,因此您将其设为nullable 字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    相关资源
    最近更新 更多