2
votes

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
The Image is not showing try writing the ErrorWowo Ot
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'dbfirsttest.Models.testdatabaseContext' while attempting to activate 'dbfirsttest.Controllers.HomeController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)givexa
It looks like an issue with your sevice injection..can you post where you are doing that?Ben Krueger
I have not added anything in startup services, with code first approach i added a connection string however in db first approach is it needed?givexa
Can you post the code for your entire controller?Ben Krueger

2 Answers

4
votes

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.

2
votes

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")));