Unable to resolve service for type in .NET 5 with entity framework scaffolding

DMO 20 Reputation points
2023-02-07T17:13:46.1933333+00:00

Hi I am trying to do a website using .NET 5 with some entity framework 3.1.21.

I get this error on my Comments/index page

I read an article on the Microsoft docs I'm pretty sure about this error but I can't find it now.

can anyone point me in the right direction?

thanks in advance,

    InvalidOperationException: Unable to resolve service for type 'EC.DataAccess.EF.Context.EcContext' while attempting 
InvalidOperationInvalidOperationException: Unable to resolve service for type 'EC.DataAccess.EF.Context.ECContext' while attempting to activate 'EC09.Controllers.CommentsController'.InvalidOperationException: Unable to resolve service for type 'EC.DataAccess.EF.Context.ECContext' while attempting to activate 'EC09.Controllers.CommentsController'.
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,140 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2023-02-08T02:36:30.2566667+00:00

    Hi @DMO

    In the Startup ConfigureServices method, you should register the database context like this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    
        services.AddDbContext<EcContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("EcContextconnectionstring")));
    }
    

    You can set the connection string in the appsettings.json file:

    "ConnectionStrings": {
      "EcContextconnectionstring": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-2;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
    

    And the database context as below:

        public class EcContext : DbContext
        {
            public EcContext (DbContextOptions<EcContext> options)
                : base(options)
            {
            }
    
            public DbSet<Movie> Movie { get; set; }
        }
    

    More detail information, refer to the following tutorials:

    Part 4, add a model to an ASP.NET Core MVC app

    Part 5, work with a database in an ASP.NET Core MVC app

    Tutorial: Get started with EF Core in an ASP.NET MVC web app


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.
    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Michael Taylor 47,716 Reputation points
    2023-02-07T19:32:56.11+00:00

    EF 3.1 is EOL. You need to update to at least EF 6. .NET 5 is also EOL and you need to update to .NET 6 (or 7).

    Once you've upgraded then ensure that you're calling AddDbContext when configuring your app services at startup. This will register your DbContext and then you can use it as a parameter to your CommentsController constructor.

    //Sample startup
    ...
    services.AddDbContext<EcContext>(options => {
       options.UseSqlServer("your connection string");
    });
    
    //You can now use EcContext in constructors
    public class CommentsController : Controller
    {
       public CommentsController ( EcContext context )   
       {   
          _context = context;
       }
    
       private readonly EcContext _context;
    }
    
    0 comments No comments

  2. DMO 20 Reputation points
    2023-02-08T00:24:09.37+00:00

    Does .NET 6 use the startup file? can you add that statement to the program.cs?

    0 comments No comments

  3. DMO 20 Reputation points
    2023-02-08T00:25:30.84+00:00

    this is my Startup.cs file so far. I haven't edited it yet. it's just the default auto generated stuff

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace EC09
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
            }
    
            //My stuff
            //public void ConfigureServices(IServiceCollection services)
            //{
            //    //modify the ForumManageContext to your generated dbcontext model
            //    services.AddDbContext<ForumManageContext>();
    
            //    services.AddRazorPages();
            //}
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    
    

  4. DMO 20 Reputation points
    2023-02-09T00:44:21.3466667+00:00

    Hey that actually worked. thanks very much.

    0 comments No comments