我使用身份服务器aspNetUsers表,其中放置了所有已注册的用户。我用userId和我的自定义表之间的外主键关系来构建自定义表,从这里我要建立m2m关系。用户的编程语言及其知识。但是,即使使用JOIN TABLE
也不能使用。在受保护的覆盖void OnModelCreating(ModelBuilder modelBuilder)
方法上,它给了我这个错误:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_userPLs_Knowledge_KnowledgeId". The conflict occurred in database "try1", table "dbo.Knowledge", column 'KnowledgeId'
我的代码如下:
public class ApplicationUser : IdentityUser
{
//s
public string ImgPath { get; set; }
public UserPL UserPL { get; set; }
}
//USERiD HERE IS THE FOREIGN KEY CONNECTED WITH THE PRIMARY KEH OF THE ID
//OF THE ApplicationUser AND IT IS WORKING
public class UserPL
{
public string UserPLId { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
public string ProgrammingLanguageId { get; set; }
public string KnowledgeId { get; set; }
public ProgrammingLanguage ProgrammingLanguage { get; set; }
public Knowledge Knowledge { get; set; }
public ApplicationUser applicationUser { get; set; }
}
public class ProgrammingLanguage
{
public string ProgrammingLanguageId { get; set; }
public string Name { get; set; }
public ICollection<UserPL> UserPLs { get; set; }
}
public class Knowledge
{
public string KnowledgeId { get; set; }
public string Name { get; set; }
public ICollection<UserPL> UserPLs { get; set; }
}
//THE CONEXT
public class AuthenticationContext : IdentityDbContext
{
public AuthenticationContext(DbContextOptions options) : base(options)
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<UserPL> userPLs { get; set; }
public DbSet<ProgrammingLanguage> ProgrammingLanguages { get; set; }
public DbSet<Knowledge> Knowledges { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//this is not working,it gives the above error
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<UserPL>().HasKey(sc => new { sc.ProgrammingLanguageId, sc.KnowledgeId });
modelBuilder.Entity<UserPL>()
.HasKey(bc => new { bc.KnowledgeId, bc.ProgrammingLanguageId });
modelBuilder.Entity<UserPL>()
.HasOne(bc => bc.Knowledge)
.WithMany(b => b.UserPLs)
.HasForeignKey(bc => bc.KnowledgeId);
modelBuilder.Entity<UserPL>()
.HasOne(bc => bc.ProgrammingLanguage)
.WithMany(c => c.UserPLs)
.HasForeignKey(bc => bc.ProgrammingLanguageId);
//THIS WORKS
modelBuilder.Entity<ApplicationUser>()
.HasOne<UserPL>(s => s.UserPL)
.WithOne(ad => ad.applicationUser)
.HasForeignKey<UserPL>(ad => ad.UserId);
}