EFCore versions, we don't have GUI to manage the DB-entities & dbContext like we used to have with EF6 (or EF5/4 version). With EFCore we've the Scaffold-DbContext command which helps us to create entities & DB context from our DB-objects.
Let's see how to use Scaffold-DbContext:
Assume we're connecting with SQL Server so after creating a sample project you'll have to install EFCore related libraries as mentioned below.
Install entity-framework-core for SQL Server, at this time 3.1.9 is the latest stable version
- Microsoft.EntityFrameworkcore
- Microsoft.EntityFrameworkCore.SqlServer
To use Scaffold-DbContext, following two NuGet packages are required
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Design
Let's say we've two DB tables (e.g. dbo.Employees & dbo.Users )
Now let's see how to use Scaffold-DbContext to create c-sharp entities for those two tables:
Open Package manager console
Visual Studio => Tools => NuGet Package Manager => Package Manager Console
Your package manager console will appear like this:
Now run Scaffold-dbContext command like this:
- To create a separate directory for dbContext use -ContextDir option
- To create custom dbContext name use -Context option
the command is something like this.
Before executing this command make sure you've selected the "Default project" where you want to create the entities & DB context (e.g. TestWebApp.DataAccess)
Scaffold-DbContext 'Data Source=localhost;Initial Catalog=TestDatabase;Integrated Security=True' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables "Dbo.Employees","Dbo.Users" -ContextDir "MyContextDir" -Context MyTestContext
Atest successful execution of this command your "Package manager console" will
be like this.
And in your project, you can observe the related entities for your db-objects & your context
Comments
Post a Comment