Reputation: 3437
I'm trying to build a simple CRUD app using Blazor in Visual Studio 2019 - I have watched over 7 tutorials between YouTube, PluralSight, and Channel 9, and in all of them, they use Entity Framework Core to create the Database and Tables from within Visual Studio, which is understandable as code-first is ideal architecture.
However my database and tables already exist, and for the first step, I just want to connect the Blazor app to a table and read it into UI columns.
How would I accomplish the step of importing an existing database table in Visual Studio 2019? If there is documentation on the web that refers specifically to accomplishing this in Blazor, please do point me to that, as I'm not able to find anything outside of some old ASP.Net MVC docs.
Upvotes: 15
Views: 11604
Reputation: 21
Rene's answer is correct it just needs 2 amendments:
You need to add a / before the > on the last package reference.
You will also need to reference "Microsoft.EntityFrameworkCore.Design" Version="3.1.1"
Upvotes: 2
Reputation: 3711
Add the following Packages to your project:
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
Add your database connection string to appsettings.json
{
"ConnectionStrings": {
"MyConnection": "Server=tcp:<yourServer>,1433;Initial Catalog=<yourDatabase>;Persist Security Info=False;User ID=<yourDatabaseUserName>;Password=<yourDatabaseUserPassword>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"
}
}
Open PackageManagerConsole and type
Scaffold-DbContext -Connection name=MyConnection -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -Force
This will create a Models folder in your project containing MyDbContext.cs plus a
<TableName>.cs
-file for each table in your database.
Note: For the first import of your database you don't need the -Force option in the Scaffolding. It will be needed though, if you make changes in your database after the first import and want to update your cs-classes afterwards.
Upvotes: 17
Reputation: 5865
In our company we are using EF Core Power Tools for generating the context and the model classes for Entity Framework Core.
You can find the corresponding documentation under https://github.com/ErikEJ/EFCorePowerTools/wiki/Reverse-Engineering. With this tool you can directly generate the classes within Visual Studio and you also can store the configuration that you easily can update your classes if the database changes.
Upvotes: 9