locked
How to migrate from Ado.Net into EF core framework RRS feed

  • Question

  • User2038750770 posted

    Currently I am using ado.net frame work in Asp.Net core project , I would like to change in to Entity frame work core from Ado.Net for  further development in the same project. I want to keep  the existing ADO.NET connection and the same connection have to be used for EF core framework. If the same connection cannot be used for EF,  I can use another connection string to the same database 

    I have already  installed all the necessary file needed for Entity frame work.

    I tried all the possible ways but still not working , Please I am looking for  for the help from expertise who can  explain with each steps in simple way and easy to follow. My existing ado.net code is given below

    Existing Appsetting file

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "ConnectionSetting": {
        "ConnectionString": "Data Source=myServer\\SQLEXPRESS;Initial Catalog=TestDatabase; user id=sa; password=password;" 
      }
    
       
      

    Startup file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;
    using MyProject.GO.Common;
    using MyProject.GO.UI.Models;
    
    namespace MyProject.GO.UI
    {
        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.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
                //services.AddDbContextPool<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                services.AddSession(options =>
                {
                    options.IdleTimeout = TimeSpan.FromHours(5);
                });
                services.AddMvc();
                services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
                services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddOptions();
            }
    
            // 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.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles(new StaticFileOptions()
                {
                    OnPrepareResponse = context =>
                    {
                        context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
                        context.Context.Response.Headers.Add("Expires", "-1");
                    }
                });
    
                app.UseSession();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    

    Home Controller

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Data;
    using Microsoft.AspNetCore.Mvc;
    using MyProject.GO.UI.Models;
    using MyProject.GO.Business;
    using Microsoft.Extensions.Options;
    using MyProject.GO.Common;
    using System.Security.Claims;
    using Microsoft.AspNetCore.Identity;
    using MyProject.GO.UI.Sevices;
    using Microsoft.AspNetCore.Http;
    using MyProject.GO.Common.Models;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Newtonsoft.Json;
    using System.Globalization;
    
    namespace MyProject.GO.UI.Controllers
    {
        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }
            IOptions<ConnectionSetting> connectionSettings;
            public HomeController(IOptions<ConnectionSetting> connectionSettings)
            {
                this.connectionSettings = connectionSettings;
            }
    
            public IActionResult About()
            {
                ViewData["Message"] = "Your application description page.";
    
                return View();
            }

    Employee Controller

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.Extensions.Options;
    using MyProject.GO.Business;
    using MyProject.GO.Common;
    using MyProject.GO.UI.Models;
    using MyProject.GO.UI.Sevices;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    namespace MyProject.GO.UI.Controllers
    {
        public class EmployeeController : Controller
        {
            IOptions<ConnectionSetting> connectionSettings;
    
    
            //private readonly AttendanceDbContext _dbcontext;
    
            //public EmployeeController(AttendanceDbContext dbcontext)
            //{
            //    _dbcontext = dbcontext;
    
            //}
    
    
            public EmployeeController(IOptions<ConnectionSetting> connectionSettings)
            {
                this.connectionSettings = connectionSettings;
    
            }
    
            public IActionResult SessionExpiry()
            {
    
                return View();
            }

    AttendanceDbContext.cs

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace MyProject.GO.UI.Models
    {
        public class AttendanceDbContext : DbContext
        {
            public AttendanceDbContext(DbContextOptions<AttendanceDbContext> options)
                : base(options)
            {
    
            }
            public DbSet<CustomerModel> Customer { get; set; }
            
        }
    }
    

    Please advise me with the steps to follow which can be easily followed.

    With Many Thanks  and it would be very great help to me

    Thursday, October 17, 2019 7:19 PM

Answers

  • User475983607 posted

    This thread is suspiciously similar to another thread posted today.

    https://forums.asp.net/t/2160751.aspx?moving+to+Ado+net+core+into+ef+core+error+InvalidOperationException+Multiple+constructors+accepting+all+given+argument+types+have+been+found+

    First, the code throws an exception because there is not ConnectionStrings node in the configuration file.

    services.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));

    Fix your appsetting.json file.

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=GenericIdentity;Trusted_Connection=True;MultipleActiveResultSets=true",
        "AdoConnectionString": "Data Source=MyDatabase;Initial Catalog=TestData; user id=sa; password=mypassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }

    Then reference the connection key.  For example.

    services.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    You can remove this code from the startup...  

    services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));

    and simply pass the configuration to your constructor.

    namespace MyProject.GO.UI.Controllers
    {
        public class HomeController : Controller
        {
    	public readonly IConfiguration Configuration;
    		 
            public HomeController(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    		
            public IActionResult Index()
            {
    	    string defaultConnectionString = Configuration.GetConnectionString("DefaultConnection");
    	    string adoConnectionString = Configuration.GetConnectionString("AdoConnectionString")
                return View();
            }
    		
            public IActionResult About()
            {
                ViewData["Message"] = "Your application description page.";
    
                return View();
            }

    You can get fancy and pass IOptions but your configuration is pretty simple.   I use the IOptions pattern when passing configuration to a specific class or service.    For now, you should learn and stick with the basics. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 17, 2019 8:11 PM
  • User1634355159 posted

    Hi systemthreep,

    The default connection database method in asp.net core is like this:

     "ConnectionStrings": {
       "DefaultConnectionString": "Data Source=(localdb)\\mssqllocaldb;Database=MVCCore3projContext-d321cd94-ea13-4141-bdd7-85f12e731fd2;Trusted_Connection=True;MultipleActiveResultSets=true;"
      },

    But in you code,I found you want to use this way:

    "ConnectionSetting": {
        "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MVCCore3projContext-d321cd94-ea13-4141-bdd7-85f12e731fd2;MultiSubnetFailover=true"
      }

    You could Configure like this:

    public void ConfigureServices(IServiceCollection services)
            {      
               
                services.AddServerSideBlazor();
                services.AddControllersWithViews();
                //services.AddDbContext<Yourdbcontext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));//This is the default method
                services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
            }

    And use the dbcontext like this:

            //private readonly Yourdbcontext _context;//This is the default way
            private readonly IOptions<ConnectionSetting> connectionSettings;
            public DbContextOptions<Yourdbcontext> dbContextOptions;
            public TestController(Yourdbcontext context, IOptions<ConnectionSetting> connectionSettings, DbContextOptions<Yourdbcontext> dbContextOptions)
            {
                //_context = context;
                this.connectionSettings = connectionSettings;
                this.dbContextOptions = dbContextOptions;
            }
    public async Task<IActionResult> Index() { //var model = await _context.Products.ToListAsync();//this is EF dbContextOptions = new DbContextOptionsBuilder<Yourdbcontext>() .UseSqlServer(connectionSettings.Value.ConnectionString) .Options; var _context2 = new Yourdbcontext(dbContextOptions); var model2 = await _context2 .Products.ToListAsync(); return View(model); }

    Best Regards,

    Lewis

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 18, 2019 9:24 AM

All replies

  • User475983607 posted

    This thread is suspiciously similar to another thread posted today.

    https://forums.asp.net/t/2160751.aspx?moving+to+Ado+net+core+into+ef+core+error+InvalidOperationException+Multiple+constructors+accepting+all+given+argument+types+have+been+found+

    First, the code throws an exception because there is not ConnectionStrings node in the configuration file.

    services.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));

    Fix your appsetting.json file.

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=GenericIdentity;Trusted_Connection=True;MultipleActiveResultSets=true",
        "AdoConnectionString": "Data Source=MyDatabase;Initial Catalog=TestData; user id=sa; password=mypassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }

    Then reference the connection key.  For example.

    services.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    You can remove this code from the startup...  

    services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));

    and simply pass the configuration to your constructor.

    namespace MyProject.GO.UI.Controllers
    {
        public class HomeController : Controller
        {
    	public readonly IConfiguration Configuration;
    		 
            public HomeController(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    		
            public IActionResult Index()
            {
    	    string defaultConnectionString = Configuration.GetConnectionString("DefaultConnection");
    	    string adoConnectionString = Configuration.GetConnectionString("AdoConnectionString")
                return View();
            }
    		
            public IActionResult About()
            {
                ViewData["Message"] = "Your application description page.";
    
                return View();
            }

    You can get fancy and pass IOptions but your configuration is pretty simple.   I use the IOptions pattern when passing configuration to a specific class or service.    For now, you should learn and stick with the basics. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 17, 2019 8:11 PM
  • User1120430333 posted

    I used what's being talked about in the link.

    https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

    I show how to use what's in the link above in the below thread.

    https://forums.asp.net/t/2160579.aspx?DataBase+Connection+In+appsettings+json

    Thursday, October 17, 2019 9:27 PM
  • User1634355159 posted

    Hi systemthreep,

    The default connection database method in asp.net core is like this:

     "ConnectionStrings": {
       "DefaultConnectionString": "Data Source=(localdb)\\mssqllocaldb;Database=MVCCore3projContext-d321cd94-ea13-4141-bdd7-85f12e731fd2;Trusted_Connection=True;MultipleActiveResultSets=true;"
      },

    But in you code,I found you want to use this way:

    "ConnectionSetting": {
        "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MVCCore3projContext-d321cd94-ea13-4141-bdd7-85f12e731fd2;MultiSubnetFailover=true"
      }

    You could Configure like this:

    public void ConfigureServices(IServiceCollection services)
            {      
               
                services.AddServerSideBlazor();
                services.AddControllersWithViews();
                //services.AddDbContext<Yourdbcontext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));//This is the default method
                services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
            }

    And use the dbcontext like this:

            //private readonly Yourdbcontext _context;//This is the default way
            private readonly IOptions<ConnectionSetting> connectionSettings;
            public DbContextOptions<Yourdbcontext> dbContextOptions;
            public TestController(Yourdbcontext context, IOptions<ConnectionSetting> connectionSettings, DbContextOptions<Yourdbcontext> dbContextOptions)
            {
                //_context = context;
                this.connectionSettings = connectionSettings;
                this.dbContextOptions = dbContextOptions;
            }
    public async Task<IActionResult> Index() { //var model = await _context.Products.ToListAsync();//this is EF dbContextOptions = new DbContextOptionsBuilder<Yourdbcontext>() .UseSqlServer(connectionSettings.Value.ConnectionString) .Options; var _context2 = new Yourdbcontext(dbContextOptions); var model2 = await _context2 .Products.ToListAsync(); return View(model); }

    Best Regards,

    Lewis

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 18, 2019 9:24 AM
  • User-1355965324 posted

    Lewis

    According to your reply I changed the connection  in appsetting as given below. Please can you advise me is that correct ? . i cannot change the ConnectionSetting and connectionString because it will affect the  existing program in Ado.Net. So I would like to keep two connection

    "ConnectionSetting": {
    "ConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa; password=password;",
    "DefaultConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa;password=password!;MultipleActiveResultSets=true",

     

    Please can you advise me

    Friday, October 18, 2019 11:04 AM
  • User-1355965324 posted

    The following error is coming when I run the program after the changes you advised

    Argument null exception , Value cannot be null error is coming

    public void ConfigureServices(IServiceCollection services)
    {
    //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString"));//This is the default method
    services.AddDbContext<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));
    services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
     
    {
    options.IdleTimeout = TimeSpan.FromHours(5);
    });
    services.AddMvc();
    //services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddOptions();
    }

    Friday, October 18, 2019 11:23 AM
  • User475983607 posted

    polachan, your code specifically tries to read the ConnectionString node.  

    services.AddDbContext<AttendanceDbContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));

    The solution is very simple and explained several times.  You must add a connection strings node to the appsettings.json file if you want to use the GetConnectionString() method.  

    {
      "ConnectionStrings": {
        "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=GenericIdentity;Trusted_Connection=True;MultipleActiveResultSets=true",
      },

    If you want to use your custom solution then use proper syntax is illustrated below.

    Your configuration.

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionSetting": {
        "ConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa; password=password;",
        "DefaultConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa;password=password!;MultipleActiveResultSets=true"
      }
    }
    services.AddDbContext<AttendanceDbContext>(options => 
    	options.UseSqlServer(Configuration["ConnectionSetting:DefaultConnectionString"]));

    The reference documentation covers syntax as pointed out in your similar threads.  Read the documentation.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.0

    Friday, October 18, 2019 11:29 AM
  • User-1355965324 posted

    Lewis

    When I apply  your code in controller , the following error is coming

    private IOptions<ConnectionSetting> _connectionSettings;
            public DbContextOptions<AttendanceDbContext> dbContextOptions;
    
           
    
            public EmployeeController(IOptions<ConnectionSetting> connectionSettings)
            {
                this.connectionSettings = connectionSettings;
                this.dbContextOptions = dbContextOptions;  // Error : Assignment made to same variable ; did you mean to assign somethingelse
    } public IActionResult SessionExpiry() { return View(); } public IActionResult EmployeeSetup() { if (HttpContext.Session.GetInt32("UserID") != null) { ViewBag.UserDepots = EmployeeService.GetUserDepots(HttpContext.Session.GetInt32("UserID") ?? 0, connectionSettings); ViewBag.UserDepartments = EmployeeService.GetUserDepartments(HttpContext.Session.GetInt32("UserID") ?? 0, connectionSettings); ViewBag.Designations = EmployeeService.GetDesignation(connectionSettings); ViewBag.Menu = HttpContext.Session.GetObjectFromJson<List<MenuViewModel>>("MyMenu"); return View(); } else { return RedirectToAction("SessionExpiry", "Employee"); } }

    Friday, October 18, 2019 11:36 AM
  • User-1355965324 posted

    Now I think framework is working fine   in the line in startup.cs 

    services.AddDbContext<AttendanceDbContext>(options  =>options.UseSqlServer(Configuration["ConnectionSetting:DefaultConnectionString"])); // it is working now

    But the the value into dbContextOptions is  null in  Home controller

     IOptions<ConnectionSetting> connectionSettings;
            public DbContextOptions<AttendanceDbContext> dbContextOptions; // The Value is null is coming in dbContextOptions
            public HomeController(IOptions<ConnectionSetting> connectionSettings)
            {
                this.connectionSettings = connectionSettings;
                this.dbContextOptions = dbContextOptions;
            }
    
            public IActionResult About()
            {
                ViewData["Message"] = "Your application description page.";
    
                return View();
            }

    Friday, October 18, 2019 11:55 AM
  • User475983607 posted

    Why are you passing the DbContext Options when you already set the options in the start up?  What are you trying to do?  Get the connection string? Pass the DbContext?

    The follow code passes the DbContext and shows how to get to the connection strings from the Options.  Keep in mind, the code example assumes your Options pattern is coded correctly which is a long shot.

    private readonly ConnectionSettingOptions Options
    private readonly AttendanceDbContext _attendanceDbContext;
    
    public HomeController(IOptions<ConnectionSettingOptions> options, AttendanceDbContext attendanceDbContext)
    {
    	_attendanceDbContext = attendanceDbContext;
    	Options = options.Value;
    }
    
    [HttpGet]
    public IActionResult Index()
    {
    string DefaultConnectionString = Options.ConnectionSetting["DefaultConnectionString"];
    return Content(DefaultConnectionString);
    }
        public class ConnectionSettingOptions
        {
            public Dictionary<string, string> ConnectionSetting { get; set; }        
        }
    services.Configure<ConnectionSettingOptions>(Configuration);




    Friday, October 18, 2019 12:11 PM
  • User-1355965324 posted

    I cannot change  the  variable  this.connectionSettings that will afftect the existing program.

    Now I am halfway through  to change from ado.net into ef.

    When I debug the attendanceDbContext the following error is  showed when I bring the cursor over  attendanceDbContext  while debug mode

    Change Traccker : ATtendancedbcontext:changetracker threw an exception of type 'system.Invalidoperation Exception
    Model : ATtendancedbcontext:Model threw an exception of type 'system.Invalidoperation Exception

    Any idea the reason for this error

    IOptions<ConnectionSetting> connectionSettings;  // I cannot change this settings it will affect the other module
    private readonly AttendanceDbContext _attendanceDbContext;
    public HomeController(IOptions<ConnectionSetting> connectionSettings, AttendanceDbContext attendanceDbContext)
    {
    this.connectionSettings = connectionSettings;
    _attendanceDbContext= attendanceDbContext; //when I debug  the variable the error is showed 
    }

    Is there any problem in my AttendancedbContext 

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace myproject.GO.UI.Models
    {
        public class AttendanceDbContext : DbContext
        {
            public AttendanceDbContext(DbContextOptions<AttendanceDbContext> options)
                : base(options)
            {
    
            }
            public DbSet<CustomerModel> Customer { get; set; }
            
        }
    }
    

    Friday, October 18, 2019 12:58 PM
  • User475983607 posted

    polachan

    I cannot change  the  variable  this.connectionSettings that will afftect the existing program.

    This post is getting too confusing.  As far as I can tell, you changed the configuration which affects your options class.  So in effect you have to change the class unless you are using a Dictionary.  Unfortunately, we cannot see your Options class.

      "ConnectionSetting": {
        "ConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa; password=password;",
        "DefaultConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa;password=password!;MultipleActiveResultSets=true"
      }

    The error indicates you are doing something wrong in your code but you did not post the code.  I'm not sure why?

    I don't understand why you are making this very simple configuration so complicated.  Why can't you simply keep your custom ConnectionSetting node and add the ConnectionStrings node for use with the DbContext?

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa; password=password;",
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionSetting": {
        "ConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyTestData; user id=sa; password=password;",
      }
    }

    Then your original startup code will just work.

    services.AddDbContext<AttendanceDbContext>(options => 
    options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection")));

    Or you can reuse the same connection string by simply using proper syntax as explained above.

    services.AddDbContext<AttendanceDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("ConnectionSetting:ConnectionString")));

    Friday, October 18, 2019 1:25 PM
  • User-1355965324 posted

    Now I am getting another error 

    contexttype:Declaring mathod error '((System.RuntimeType)options.ContextType).DeclaringMethod' threw an exception of type 'System.InvalidOperationException'.

    I  think Entityframe work is  working now  but when I debug,   this error is coming in debug mode. 

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace MyProject.GO.UI.Models
    {
        public class AttendanceDbContext : DbContext
        {
            public AttendanceDbContext(DbContextOptions<AttendanceDbContext> options)  // Error is coming here when I 
                : base(options)
            {
    
            }
            public DbSet<CustomerModel> Customer { get; set; }
            
        }
    }
    

    Appsetting

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=My Server\\SQLEXPRESS;Initial Catalog=MyData; user id=sa; password=password!;"
      },
        "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
            "Default": "Warning"
          }
        },
        "ConnectionSetting": {
          "ConnectionString": "Data Source=MyServer\\SQLEXPRESS;Initial Catalog=MyData; user id=sa; password=Password;"
         
        }
    
    
      }
    

    Startup

      public void ConfigureServices(IServiceCollection services)
            {
       services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
    services.AddDbContext<AttendanceDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddSession(options =>
                {
                    options.IdleTimeout = TimeSpan.FromHours(5);
                });
                services.AddMvc();
                //services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
                services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddOptions();
            }

    Friday, October 18, 2019 3:25 PM
  • User475983607 posted

    Change the configuration to...

    services.AddDbContext<AttendanceDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    Friday, October 18, 2019 5:48 PM
  • User-1355965324 posted
    services.AddDbContext<AttendanceDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    I had already done that changes in my code ,  but the  error is coming  while debugging. 

    Friday, October 18, 2019 7:54 PM
  • User475983607 posted

    I had already done that changes in my code ,  but the  error is coming  while debugging. 

    Then you must have a code bug.  I can't reproduce the error.  Plus the error has misspellings so I assume it is not the actual error.

    Friday, October 18, 2019 8:04 PM