![](/img/trans.png)
[英]How to implement Asp.net identity with existing database using database first approach in asp.net mvc core
[英]How to read tables in asp.net core, with database first approach
因此,我在 SQLEXPRESS 中创建了一个新数据库和一个表,我还用随机信息填充了表,并在 Nuget 控制台 -> Scaffold-DbContext "Server=.\SQLExpress;Database=testdb;Trusted_Connection=True;" 中使用了关键字 Microsoft.EntityFrameworkCore.SqlServer -OutputDir 模型。 程序成功创建模型,所以我只想output的信息,所以我创建了一个新的apicontroller,用[HttpGet],并注入创建的testdbcontext,它是为了获取有关数据库表的信息,所以总之我创建了以下方法。
[HttpGet("All")]
public IActionResult GetAll()
{
var obj = _db.Mobiletables.ToList();
return Ok(obj);
}
但是,当我 go 到 localhost/home/all 时,我收到以下错误 我在做什么错,我只想使用 DB First Approach 方法从数据库中读取信息到 api。
您的 controller 代码看起来是正确的,但是根据您对“我没有在启动服务中添加任何内容”的评论,您在 Startup.cs 中缺少类似的内容(特别是 AddDbContext 行):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-5.0
您仍然需要设置上下文,以便在注入时可以使用它。
您的_db
需要在 class 构造函数中初始化
public YOURController(YOURDbContext con)
{
_db= con;
}
如果您的连接字符串在appsettings.json
中,请将其添加到ConfigureServices
中的startup.cs
services.AddDbContext<YOURDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("connstr")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.