我一直在使用ASP.NET Web表单和个人身份验证设置来开发项目,该设置使用实体框架在表AspNetUsers上创建用户。
因此,我创建了一个名为Department
的新类,该类具有一个deptId
作为主键。我尝试修改IdentityModels.cs代码以将deptId
添加为AspNetUsers中的外键。
下面的代码是我为尝试实现外键而添加的。
public class ApplicationUser : IdentityUser
{
public ICollection<ApplicationUser> ApplicationUsers { get; set; }
public string isVerified { get; set; }
// Foreign key to customer
[ForeignKey("Department")]
public int deptId { get; set; }
public virtual Department Department { get; set; }
public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Department> Departments { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public object User { get; internal set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
然后尝试从该行注册时出现以下错误
IdentityResult result = manager.Create(user, Password.Text);
错误如下
SqlException:INSERT语句与FOREIGN KEY冲突 约束“ FK_dbo.AspNetUsers_dbo.Departments_deptId”。冲突 表中发生在数据库“ aspnet-WebEnterprise-20190201040106”中 “ dbo.Departments”列“ deptId”。该声明已终止。
我正在做的任何明显错误或遗漏的原因都导致了吗?