在您的UserBook 模型类中,您使用int 类型的UserId 来表示ApplicationUser,但在您的ApplicationUser 模型类中,您继承了IdentityUser,其中主键Id 的类型为@987654328 @ 默认情况下,这意味着您的ApplicationUser 的Id 是string 类型。所以UserBook表中Foreignkey的主键类型会不匹配。
Solution-1:如果你保留ApplicationUser的主键Idstring类型没有问题,那么只需将UserId类型改为@987654338中的字符串@模型类如下:
public class UserBook
{
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
}
解决方案2:如果要将ApplicationUser的主键Id从默认的string类型更改为int,则指定键类型为int,而你继承IdentityUser如下:
public class ApplicationUser : IdentityUser<int>
{
public ICollection<UserBook> UserBooks { get; set; }
}
现在您必须对 Startup 类的 ConfigureServices 方法进行如下更改:
services.AddDefaultIdentity<IdentityUser<int>>() // here replace `IdentityUser` with `IdentityUser<int>`
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
现在您的模型配置(对于解决方案-1 和解决方案-2) 使用Fluent Api 应如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserBook>()
.HasKey(ub => new { ub.UserId, ub.BookId });
modelBuilder.Entity<UserBook>()
.HasOne(ub => ub.ApplicationUser)
.WithMany(au => au.UserBooks)
.HasForeignKey(ub => ub.UserId);
modelBuilder.Entity<UserBook>()
.HasOne(ub => ub.Book)
.WithMany() // If you add `public ICollection<UserBook> UserBooks { get; set; }` navigation property to Book model class then replace `.WithMany()` with `.WithMany(b => b.UserBooks)`
.HasForeignKey(ub => ub.BookId);
}