How to read tables in asp.net core, with database first approach

Viewed 451

So, I created a new database and a table in SQLEXPRESS, I also filled tables with random information, and I used key word in Nuget console -> Scaffold-DbContext "Server=.\SQLExpress;Database=testdb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models. The Program successfully created models, so I just wanted to output the information, so I created a new apicontroller, with [HttpGet], and injected the created testdbcontext which was created to get information about the database tables, so In a word I created the following method.

 [HttpGet("All")]

    public IActionResult GetAll() 
    {
        var obj = _db.Mobiletables.ToList();

        return Ok(obj);
    }

However, when I go to localhost/home/all I get the following error enter image description here What am I doing wrong, I just want to read information from the database to api, using DB First Approach method.

2 Answers

Your controller code looks correct, but based off of your comment of "I have not added anything in startup services" you are missing something like this in Startup.cs (specifically the AddDbContext line):

    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

You still need to set up your context so that it can be used when it is injected.

Your _db need to be initialized in your class constructor

public YOURController(YOURDbContext con)
{
    _db= con;
}

If you Connection String is in appsettings.json add this to startup.cs inside ConfigureServices

services.AddDbContext<YOURDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("connstr")));
Related