【发布时间】:2019-08-08 10:50:14
【问题描述】:
我在将 Microsoft.AspNetCore.Identity.EntityFrameworkCore 添加到我的项目时遇到问题。我已经创建了数据库(代码优先),现在我需要添加一些表,这是创建登录和注册系统所必需的。
我已经尝试过一些教程如何做到这一点,但我总是遇到同样的错误。可能我忘记了。
我有 2 个控制器,Home 和 Account。 Home是对产品和产品列表进行操作。帐户必须让我注册用户并让他们登录。
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = model.Email, Email = model.Email };
var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Main_menu", "Home");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View();
}
}
还有我的 Context(我正在创建 3 个表,但由于 IdentityDbContext,db 有更多)
public class ProductContext : IdentityDbContext
{
public Microsoft.EntityFrameworkCore.DbSet<Product> Products { get; set; }
public Microsoft.EntityFrameworkCore.DbSet<List> Lists { get; set; }
public Microsoft.EntityFrameworkCore.DbSet<ProductList> ProductLists { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlite("Data Source=database.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ProductList>()
.HasKey(pl => new { pl.ProductId, pl.ListId });
modelBuilder.Entity<ProductList>()
.HasOne(pl => pl.Product)
.WithMany(p => p.ProductList)
.HasForeignKey(pl => pl.ProductId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ProductList>()
.HasOne(pl => pl.List)
.WithMany(l => l.ProductList)
.HasForeignKey(pl => pl.ListId)
.OnDelete(DeleteBehavior.Cascade);
}
}
和我的观点:
@model RegisterViewModel
@{
ViewData["Title"] = "Register";
}
<h1>Rejestracja</h1>
<div class="row">
<div class="col-sm-12">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
Haslo:
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
Powtorz Haslo:
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Zarejestruj</button>
</form>
</div>
</div>
和启动:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ProductContext>();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
当我想移动到这个视图时,我有:
InvalidOperationException:尝试激活“Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9[Microsoft.AspNetCore.Identity.IdentityUser,Microsoft.AspNetCore.Identity.IdentityRole,PracaInz.Models.ProductContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserRole@ 时无法解析类型“PrcaInz.Models.ProductContext”的服务987654326@1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String],Microsoft.AspNetCore.Identity.IdentityRoleClaim1[System.String]]'。
是否可以将 Microsoft.AspNetCore.Identity.EntityFrameworkCore 添加到代码优先数据库?
在整个项目中,我有更多视图,我可以在它们之间移动。该错误仅在我尝试使用 Microsoft.AspNetCore.Identity.EntityFrameworkCore 时出现。 该错误涉及 Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore。 表格是空的。
当我没有 HttpPost 注册方法时,我可以移动到视图。问题是当我添加 HttpPost 方法时。
【问题讨论】:
-
您是否尝试过在
IdentityUser和另一个表之间创建关系?据我所知,它应该在那之后工作。试试看。更改实体后记得更新数据库。 -
我不需要将用户与列表链接。我只需要登录和注册系统。 IdentityTables 可以使用了,它是在 DB 中创建的。
-
你在哪一行代码遇到了异常?
-
我没听懂,我的意思是错误是当我试图用寄存器查看时
-
点击按钮时出现异常,应该调用注册函数
标签: c# database asp.net-core model-view-controller entity-framework-core