Existing SQL Server

Generating a model from an existing database .Net Core 2.0

In a folder that will contain your demo project type the following command:
dotnet new console for a console application or dotnet new mvc for a MVC or Web API application

Add the Entity Framework Core and Tools packages to the project:
This is the EF Core provider for SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

This package contains the Entity Framework Core commands. Both of these packages are required for any Entity Framework Core application that targets SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.Tools

The final package is required for supporting the scaffolding of the model.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design

Test if Entity Framework is available
dotnet ef -h

Now use the DbContext Scaffold command to generate the model passing two arguments:

  • a connection string
  • a provider
  • dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorks;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

    dotnet ef dbcontext scaffold "Server=localhost,1433\\Catalog=AdventureWorks;Database=AdventureWorks;User=SA;Password=;" Microsoft.EntityFrameworkCore.SqlServer -o Models

    Once you have executed the command, you will see that a folder named Models has been created in the project folder, containing a collection of class files representing the entities.
    You can find also a class file containing the DbContext class.
    The DbContext class will take the name of the database plus “Context”.
    You can override this using the -c or –context option e.g.
    dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -c "AdventureContext"