[英]Cannot create a DbSet for 'IdentityUser' because this type is not included in the model for the context
Trying to all code to get all users with their roles so I had to change up my code a bit and ran into this error. 尝试使用所有代码来让所有用户都拥有他们的角色,因此我不得不稍微修改一下代码并遇到此错误。 I'm not sure what I did wrong, I narrowed it down to my startup.cs and ApplicationDBContect
class. 我不确定自己做错了什么,将其范围缩小到了startup.cs和ApplicationDBContect
类。 I have no errors, and I might need a migration, haven't done that to prevent causing more issues. 我没有任何错误,并且可能需要进行迁移,但这样做并没有阻止引起更多问题。
I reference Stackoverflow question and had other errors. 我参考了Stackoverflow问题,并遇到了其他错误。
ApplicationDBContext.cs ApplicationDBContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUserRole>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
Startup.cs 启动文件
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
I see you are extending both IdenityUser
and IdentityRole
with ApplicationUser
and ApplicationRole
respectively but you did not add them in your identity service registration. 我看到您分别使用ApplicationUser
和ApplicationRole
扩展了IdenityUser
和IdentityRole
,但是您没有在身份服务注册中添加它们。 So update your identity service registration in startup as follows: 因此,请在启动时更新您的身份服务注册,如下所示:
services.AddIdentity<ApplicationUser, ApplicationRole>() // </-- here you have to replace `IdenityUser` and `IdentityRole` with `ApplicationUser` and `ApplicationRole` respectively
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.