Question

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.

1
2
1/31/2020 1:27:06 PM

Accepted Answer

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.

3
1/29/2020 5:08:54 AM

Popular Answer

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.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow