Arebhy Sridaran
Arebhy Sridaran

Reputation: 586

How to connect with microsoft sql sever with ASP.NET Core API

I'm totally new to ASP.NET. I wanted to create small API. I tried to connect that API with Microsoft Sql Server. But it gives an error which is

InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc' inside the call to 'ConfigureServices(...)' in the application startup code

My Startup.cs file is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
//using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;
using myApp.Models;

namespace myApp
{
    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)
        {
            var connection = @"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

That error is indicate in app.UseMvc(); . Can you anyone help me to solve this problem?

Upvotes: 0

Views: 1286

Answers (1)

Assaf Our
Assaf Our

Reputation: 639

after the services.AddDbContext … just add services.AddMvc() (just as the error Msg suggested )

    public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
 services.AddMvc()
        }

Upvotes: 2

Related Questions