1. Run following command to install required packages:
Install-package Microsoft.EntityFrameworkCore.SqlServer
2. For database first approach, need to run below the commands to install required tools:
Install-package Microsoft.EntityFrameworkCore.Tools
Install-package Microsoft.EntityFrameworkCore.SqlServer.Design
3. Run following command to generate data models:
Scaffold-dbcontext "server= (local);D atabase=dbname; User Id=sa; Password=password; " Microsoft.entityframeworkcore.sqlserver-outputdir Models-force-dataannotations-context "CustomDBContext"
4. Move the connection string to config file:
1) Add connection string in file Appsettings.json
{ "ConnectionStrings": { "customdbcontext": "server= (local);D atabase= DBName; User Id=sa; Password=password; " }, " Logging ": { false, " LogLevel ": { " Default ":" Warning " } }
2) Define static Dbconnectionstring property in DBContext file:
Public Partial class Customdbcontext:dbcontext { ... Public Static string Get Set ; } protected Override void onconfiguring (Dbcontextoptionsbuilder optionsbuilder) { optionsbuilder.usesqlserver (dbconnectionstring); } ... }
3) Get database connection string from Appsettings.json file and assign it to dbconnectionstring in Startup.cs file
Public void configureservices (iservicecollection services) { // Config Database connection string nuhotrscontext.dbconnectionstring = configuration.getconnectionstring ("Customdbcontext" ); ... }
Reference Links:
Https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
Https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell
Https://joonasw.net/view/asp-net-core-1-configuration-deep-dive
Setup Entity Framework Core in ASP.