无法为“ApplicationUser”创建 DbSet,因为此类型未包含在上下文模型中
Posted
技术标签:
【中文标题】无法为“ApplicationUser”创建 DbSet,因为此类型未包含在上下文模型中【英文标题】:Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context 【发布时间】:2019-08-16 20:46:27 【问题描述】:尝试使用实体框架核心添加新用户时,出现上述错误代码。我知道以前在这里有人问过这个问题,但我无法用目前找到的解决方案解决我的问题。
我正在尝试使用 asp.net 身份创建具有用户名(电子邮件)和密码的用户,但我不断收到以下错误消息:
“InvalidOperationException:无法为 'ApplicationUser',因为此类型不包含在模型中 上下文。”
我尝试弄乱了 startup.cs 文件和 Model.BlogContext 文件 正如这里的多个线程所建议的那样,但似乎无法绕过此消息。
我对此很陌生,如果我的问题不清楚,请见谅。
这是我的代码 -
ApplicationContext:
命名空间 Blog3Prog.Models 班级留言 [钥匙] 公共 int MessageId 获取;放; 公共字符串用户名 获取;放; 公共字符串 FullMessage 获取;放;
class Timeline
[Key]
public int UserId get; set;
public int Posts get; set;
public string Username get; set;
public class BlogContext : IdentityDbContext<ApplicationUser>
public BlogContext(DbContextOptions<DbContext> options) : base()
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
optionsBuilder.UseSqlServer(@"Data Source=
(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated
Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False; Database=BlogProject
;Trusted_Connection=True");
private DbSet<Message> Messages get; set;
private DbSet<Timeline> Timelines get; set;
private DbSet<ApplicationUser> applicationUsers get; set;
public DbSet<Microsoft.AspNetCore.Identity.IdentityUserClaim<Guid>>
IdentityUserClaims get; set;
public DbSet<IdentityUserClaim<string>> IdentityUserClaim get;
set;
public new DbSet<ApplicationUser> Users get; set;
protected override void OnModelCreating(ModelBuilder modelBuilder)
Startup.cs:
namespace Blog3Prog
public class Startup
public Startup(IConfiguration configuration)
Configuration = configuration;
public IConfiguration Configuration get;
// This method gets called by the runtime. Use this method to add
services to the container.
public void ConfigureServices(IServiceCollection services)
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=master;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False; Database=BlogProject
;Trusted_Connection=True"));
services.Configure<CookiePolicyOptions>(options =>
// This lambda determines whether user consent for non-essential
cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddIdentity<Blog3Prog.Models.ApplicationUser,
IdentityRole> ()
.AddEntityFrameworkStores<DbContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_2);
// This method gets called by the runtime. Use this method to configure
the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change
this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
routes.MapRoute(
name: "default",
template: "controller=Account/action=Login/id?");
);
app.UseAuthentication();
控制器:
namespace Blog3Prog.Controllers
public class AccountController : Controller
public readonly UserManager<ApplicationUser> _userManager;
public readonly SignInManager<ApplicationUser> _signInManager;
public readonly Models.BlogContext _context;
public AccountController(UserManager<ApplicationUser> userManager
,SignInManager<ApplicationUser> signInManager
, Models.BlogContext context)
_userManager = userManager;
_signInManager = signInManager;
_context = context;
[HttpGet]
public IActionResult Register()
return View();
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel vModel)
if (ModelState.IsValid)
var user = new ApplicationUser UserName = vModel.UserEmail, Email = vModel.UserEmail ;
var result = await _userManager.CreateAsync(user, vModel.Password);
if (result.Succeeded)
//await _signInManager.SignInAsync(user, false);
//return RedirectToAction("Index", "Home");
else
foreach (var error in result.Errors)
ModelState.AddModelError("", error.Description);
return View(vModel);
public IActionResult Login()
return View("Login");
查看
<h2>Registration Page</h2>
<form method="post" asp-controller="Account" asp-action="Register">
<div asp-validation-summary="All"></div>
<div>
<label asp-for="UserEmail"></label>
<input asp-for="UserEmail" />
<span asp-validation-for="UserEmail"></span>
</div>
<div>
<label asp-for="Password"></label>
<input asp-for="Password" />
<span asp-validation-for="Password"></span>
</div>
<div>
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" />
<span asp-validation-for="ConfirmPassword"></span>
</div>
<div>
<input type="submit" value="Register" />
</div>
</form>
ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blog3Prog.Models
public class ApplicationUser:IdentityUser
public int UserId get; set;
public string UserEmail get; set;
public DateTime CreatedOn get; set;
public int Points get; set;
【问题讨论】:
尝试将services.AddDbContext<DbContext>(options =>
更改为services.AddDbContext<BlogContext>(options =>
这给了我错误消息:“没有从 'Blog3Prog.Models.BlogContext' 到 'Microsoft.EntityFrameworkCore.DbContext' 的隐式引用转换。”
BlogContext
类应派生自 DBContext
。喜欢public class BlogContext: DBContext
我做了这个改变,不幸的是这并没有解决问题。但是现在当我尝试添加迁移时,我收到消息:“找到多个 DbContext。指定要使用的一个”当我通过键入指定要使用的一个时:“add-migration 190326-1412 -context BlogContext”我得到:“无法创建类型为 'BlogContext' 的对象。”不确定这是否有帮助? ""
删除这些行:services.AddScoped<BlogContext>(); services.AddScoped<DbContext>();
【参考方案1】:
这给了我错误消息:“没有隐式引用 从“Blog3Prog.Models.BlogContext”转换为 'Microsoft.EntityFrameworkCore.DbContext'。
出现此行为是因为 BlogContext 没有继承 IdentityDbContext
下面是我的示例。此示例在我的本地工作。使用您的 ApplicationUser 更改用户并添加您的其他模型。
public class BlogContext : IdentityDbContext<User>
public BlogContext(DbContextOptions options) : base()
public DbSet<User> Users get; set;
public class User:IdentityUser
这应该被添加到配置服务方法中。
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer("Your connection string");
我认为像你那样创建数据库上下文是个坏主意。
同时从您的启动中删除下一个:
services.AddScoped<BlogContext>();
services.AddScoped<DbContext>();
还有如何重构你的 BlogContext.cs:
public class BlogContext : IdentityDbContext<ApplicationUser>
public BlogContext(DbContextOptions options) : base()
public DbSet<Message> Messages get; set;
public DbSet<Timeline> Timelines get; set;
public DbSet<ApplicationUser> applicationUsers get; set;
public DbSet<IdentityUserClaim<Guid>> IdentityUserClaims get; set;
public DbSet<IdentityUserClaim<string>> IdentityUserClaim
get;
set;
【讨论】:
我收到错误消息:“InvalidOperationException:在尝试激活 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[Blog3Prog.Models. ApplicationUser,Microsoft.AspNetCore.Identity.IdentityRole,Microsoft.EntityFrameworkCore.DbContext,System.String]'。" 你能展示你的 ApplicationUser 类吗?你能显示更新的 Startup 和 BlogContext 类吗? 在我建议的代码更改后,您是否更新了数据库? 好的,我已经更新了原帖。我在更新数据库时遇到了麻烦。首先它告诉我有不止一个 DbContext。因此,当我指定“-context BlogContext”时,我收到错误消息:“尝试激活“Blog3Prog.Models.BlogContext”时无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]”的服务。” 好的。删除类“公共类 EFCoreOrganisationDb”。 DbSet 应该在 BlogContext 类中。以上是关于无法为“ApplicationUser”创建 DbSet,因为此类型未包含在上下文模型中的主要内容,如果未能解决你的问题,请参考以下文章
Dynamics 365Online ApplicationUser创建方式变更
ASP.NET MVC 5 - 身份。如何获取当前的ApplicationUser