我已经很久没有将数据从 SQL Server 数据库获取到视图了,而且发生了很多变化。我正在开发一个新应用程序,并且据我所知已经完成了正确的步骤。
定义模型:
public class LoginModel
{
public string UserId { get; set; } = null!;
public string Username { get; set; } = null!;
public string Password { get; set; } = null! ;
public short UserType { get; set; }
}
设置
DbContext
:
public class WebContext : DbContext
{
public WebContext(DbContextOptions<WebContext> options) : base(options)
{ }
public virtual DbSet<LoginModel>? Login { get; set; }
}
更新
Program.cs
:
builder.Services.AddDbContextFactory<WebContext>(
opt => opt.UseSqlServer(
builder.Configuration.GetConnectionString("WebConn")));
更新
appsettings.json
:
"ConnectionStrings": {
"WebConn": "Data Source=LAPTOP-4LUQ899E;Initial
Catalog=BookSearch;TrustServerCertificate=Yes;Trusted_Connection=True"
},
因此,在完成所有这些之后,我希望能够访问数据并将其过滤到我的视图,但根本不行,当我运行它时,我收到一个错误,希望在上下文中添加构造函数,如下所示..
public WebContext()
{
}
所以我当时以为我很奇怪,但现在我得到了错误:
尚未为此 DbContext 配置数据库提供程序。可以通过重写“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序
这曾经容易得多,我哪里出错了?
根据你的代码,它在我这边工作,我认为你收到错误的原因是你可能使用了错误的代码来激活WebContext。
AddDbContextFactory 方法与 AddDbContext 不同,如果您使用 AddDbContext,您可以通过在构造函数中添加 WebContext 直接获取服务。
如果您使用AddDbContextFactory,您需要创建dbcontext,更多详细信息,您可以参考下面的用法。
private readonly IDbContextFactory<WebContext> _contextFactory;
public ValuesController(IDbContextFactory<WebContext> contextFactory)
{
_contextFactory = contextFactory;
}
[HttpGet]
public async Task<IActionResult> Submit()
{
using (var context = _contextFactory.CreateDbContext())
{
var result = context.Login.ToList();
}
return Ok("ss");
}
结果:
另外,如何使用也可以参考这篇文章。