当尝试使用实体框架核心添加新用户时,出现上述错误代码。我知道之前已经有人问过这个问题,但是我无法用到目前为止找到的解决方案解决问题。
我正在尝试使用asp.net身份创建具有用户名(电子邮件)和密码的用户,但我不断收到以下错误消息:
“ InvalidOperationException:无法为其创建DbSet “ ApplicationUser”,因为此类型未包含在 上下文。”
我尝试弄乱了startup.cs文件和Model.BlogContext文件 如此处在多个线程上所建议的,但似乎无法绕开此消息。
我对此很陌生,很抱歉,如果我的问题不清楚。
这是我的代码-
ApplicationContext:
命名空间Blog3Prog.Models { 类消息 { [键] 公共诠释MessageId {组; } 公用字符串UserName {get;组; } 公共字符串FullMessage {get;组; }
}
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; }
}
}
答案 0 :(得分:0)
这给了我错误消息:“没有隐式引用 从'Blog3Prog.Models.BlogContext'转换为 “ Microsoft.EntityFrameworkCore.DbContext”。
出现此行为是因为BlogContext没有继承IdentityDbContext
以下是我的示例。该示例在我的本地工作。用ApplicationUser更改User并添加其他模型。
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;
}
}