skip to Main Content

Once I have added my first Migration Add-Migration InitialMigration, it display this error below,

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Failed to load configuration from file ‘C:UsersAmmadsourcereposEmployeesProjectEmployeesProjectappsettings.json’.
Unable to create a ‘DbContext’ of type ‘ApplicationDbContext’. The exception ‘Unable to resolve service for type ‘Microsoft.EntityFrameworkCore.DbContextOptions`1[EmployeesProject.Context.ApplicationDbContext]’ while attempting to activate ‘EmployeesProject.Context.ApplicationDbContext’.’ was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Please let me know the solution as I need to add the first migration. thanks

Please find my code below for just one simple class created Employee.cs

namespace EmployeesProject.Models
{
    public class Employee
    {

        public int Id { get; set; }

        public string FirstName { get; set; }
        public string MiddleName { get; set; }

        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        public int PhoneNumber { get; set; }
    }
}

My application db context class code is mentioned below

using EmployeesProject.Models;
using Microsoft.EntityFrameworkCore;

namespace EmployeesProject.Context
{
    public class ApplicationDbContext : DbContext
    {

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext>contextOptions): base(contextOptions)
        {

        }

        // Code First Approach
        public DbSet<Employee> Employees { get; set; }
    }
}

The appsetting.json code is below

{

     "ConnectionStrings": {
        "DefaultConnection": "Server": "DESKTOP-DFBVCE0;Database:Employees; User Id={username};Password:{password}; TrueServerCertificate:True"
      },
    
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }

Please find Program.cs below,

namespace Employeeproject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                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.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}

2

Answers


  1. your ConnectionStrings should be something like :

     "ConnectionStrings": {"DefaultConnection": "Server={DBAddress};Database={DBName};User Id={user};Password={Pass};MultipleActiveResultSets=true"},
    

    and your ApplicationDbContext should be something like :

    public MDBContext(IConfiguration config, DbContextOptions<MDBContext> options) : base(options)
    {
        appConfig = config;
    }
    public DbSet<testdb> Mytest { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if (!options.IsConfigured)
        {
        options.UseSqlServer(appConfig.GetConnectionString("NameOFYourCNStringInAppsettings"));
    
        }
    
    }
    

    it is better to reviewed:
    https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

    Login or Signup to reply.
  2. First i would like to suggest you to use the correct connection string as the one you are using is not in right format:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source={Sql server name];Database={Databse};Trust Server Certificate=True;Trusted_Connection=True;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    

    Program.cs:

    namespace Employeeproject
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebApplication.CreateBuilder(args);
    
                // Add services to the container.
                var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
                builder.Services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(connectionString));
    
                builder.Services.AddControllersWithViews();
    
                var app = builder.Build();
    
                // Configure the HTTP request pipeline.
                if (!app.Environment.IsDevelopment())
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
    
                app.Run();
            }
        }
    }
    

    Make sure you have installed below packages:

    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Design
    Microsoft.EntityFrameworkCore.SqlServer
    Microsoft.EntityFrameworkCore.Tools
    

    Run below commands:

    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

    OR:

    Add-Migration InitialMigration
    Update-Database
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search