在此代码中:
public static void Seed(IConfiguration configuration,
ForumDbContext dbContext,
RoleManager<IdentityRole> roleManager,
UserManager<User> userManager)
{
if (dbContext.Users.Count()==0)
CreateUsers(configuration, dbContext, roleManager, userManager)
.GetAwaiter().GetResult();
}
我在线上遇到运行时异常:
if (dbContext.Users.Count()==0)
那就是:
System.TypeInitializationException:“‘Microsoft.EntityFrameworkCore.EnumerableMethods’的类型初始值设定项引发了异常。” InvalidOperationException:序列包含多个匹配元素
我的DBContext代码如下:
public class ForumDbContext : IdentityDbContext<User>
{
public ForumDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Topic>().ToTable("Topics");
modelBuilder.Entity<Attachment>().ToTable("Attachments");
modelBuilder.Entity<Subscription>().ToTable("Subscriptions");
}
public DbSet<Topic> Topics { get; set; }
public DbSet<Subscription> Subscriptions {get;set;}
public DbSet<Attachment> Attachments { get; set; }
}
我的用户类定义如下:
public class User:IdentityUser
{
public string Discriminator { get; set; } = "User";
public string Country { get; set; } = "";
public string Signature { get; set; } = "";
public bool IncludeSignature { get; set; } = true;
public DateTime CreateDate { get; set; }
[NotMapped]
public bool SignatureFormatted = false;
[NotMapped]
public int NrPosts { get; set; }
}
将entityframework包更新到最新版本解决了问题
在@user1238784的回复中添加一些信息:
实体框架版本和 .NET 版本的联系比预期更紧密,特别是因为不匹配的版本可以很好地编译在一起。以下是正确的版本列表(实体框架品牌更改和 ASP.NET 版本供参考):