2

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.

8
  • The Image is not showing try writing the Error
    – Wowo Ot
    Jan 18, 2021 at 18:21
  • 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
    Jan 18, 2021 at 18:21
  • It looks like an issue with your sevice injection..can you post where you are doing that? Jan 18, 2021 at 18:25
  • 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
    Jan 18, 2021 at 18:27
  • Can you post the code for your entire controller? Jan 18, 2021 at 18:29

2 Answers 2

4

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://learn.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.

3
  • Oh, Thanks! In code first approach i knew i needed that, however in Database first approach i didn't imagine that i needed a connection string also, so thanks !! it worked !!
    – givexa
    Jan 18, 2021 at 18:46
  • First, i had to define it in appsettings.json, and then in startup class...
    – givexa
    Jan 18, 2021 at 18:47
  • 1
    In EF code first vs. database first is saying whether or not you want to set up your own data entity classes and repositories, or if you want EF to do it for you. Both still need to be set up like above to know which DB to interact with. Jan 19, 2021 at 19:41
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.