https://i.imgur.com/JphyUEv.png
在观看了YouTube视频https://youtu.be/PlW9dgU_aVM之后,介绍了如何在ASP.NET CORE应用程序中首先设置实体框架核心数据库的CRUD操作。
此时https://youtu.be/PlW9dgU_aVM?t=578在处理请求时发生未处理的异常,我该如何解决该问题(请参见上图)。
P.S很抱歉阅读和解密
这是针对在ASP.NET CORE应用程序中使用实体框架核心数据库的第一个CRUD操作的REST Api。
项目包括 ASP.NET Core 2.2 Web应用程序,实体框架版本2.2,Web应用程序(模型-视图-控制器)
我已经使用本地数据库生成模型和控制器,以查看其是否与防火墙或其他连接问题有关,但我99%确信它是我的代码... 我是一名初级开发人员=>,没有高级/干净的基础= <。
//Users Model - Auto generated
namespace Demo_Api.Models
{
public partial class Users
{
public int Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public string Address { get; set; }
}
}
//UsersContext - Auto generated - snip
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Demo_Api.Models
{
public partial class UsersContext : DbContext
{
public UsersContext()
{
}
public UsersContext(DbContextOptions<UsersContext> options)
: base(options)
{
}
public virtual DbSet<Users> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("server=(localdb)\\MSSQLLocalDB;Database=Users; Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");
modelBuilder.Entity<Users>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Address).HasMaxLength(10);
entity.Property(e => e.Name).HasMaxLength(10);
entity.Property(e => e.Number).HasMaxLength(10);
});
}
}
}
// UsersController - Auto generated - snip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Demo_Api.Models;
namespace Demo_Api.Controllers
{
public class UsersController : Controller
{
private readonly UsersContext _context;
public UsersController(UsersContext context)
{
_context = context;
}
// GET: Users
public async Task<IActionResult> Index()
{
return View(await _context.Users.ToListAsync());
}
// GET: Users/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// GET: Users/Create
public IActionResult Create()
{
return View();
}
// POST: Users/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Number,Address")] Users users)
{
if (ModelState.IsValid)
{
_context.Add(users);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(users);
}
// GET: Users/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users.FindAsync(id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// POST: Users/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Number,Address")] Users users)
{
if (id != users.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(users);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(users.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(users);
}
// GET: Users/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var users = await _context.Users.FindAsync(id);
_context.Users.Remove(users);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool UsersExists(int id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}
//StartUp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Demo_Api
{
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.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.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=Home}/{action=Index}/{id?}");
});
}
}
}
预期和实际结果:拥有一个REST Api,我可以通过影响现有数据库来执行CRUD操作。
处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型的服务 尝试激活时出现“ Demo_Api.Models.UsersContext” 'Demo_Api.Controllers.UsersController'。
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,bool isDefaultParameterRequired)
答案 0 :(得分:0)
您的UsersContext似乎没有连接到Asp.net的“服务”容器。
如果您打开Startup.cs
文件并查找ConfigureServices
函数,则需要在此处连接数据上下文。
这是从Microsoft文档中提取的示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}
但是,您的外观会更像:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UsersContext>(options => options.UseSqlServer("server=(localdb)\\MSSQLLocalDB;Database=Users; Trusted_Connection=True;"));
}
要给出更多信息,这是告诉Asp.net如何解析在Controller构造函数中指定的类。有关更多信息,请搜索依赖项注入或控制反转(IoC)主题。这些是用于实现此功能的技术。