Asp.NET Core uses EF to connect to SQLserver, and adopts database first to create entity model mode

1 Introduction

        .NET Core is a new, open-source, cross-platform framework for building applications for cross-operating systems, including Windows, Mac, and Linux.

        When using this tool to build a database at the beginning, the teacher used the Code First (code first) mode to encapsulate entity classes when explaining. Just another way: the database first encapsulates the entity model.

2. Use the scaffold command to generate entity classes from the database


2.1. Import EF Core related packages into the project

 

EF Core相关包
1:Microsoft.EntityFrameworkCore.SqlServer	Sql Server数据库EF提供程序
2:Microsoft.EntityFrameworkCore.Design		设计时EF共享库
3:Microsoft.EntityFrameworkCore.Tools		EF的NuGet包管理器命令工具

Note that the version of the package and the version of the project cannot be too different. If the project is 5.0, the version of the package should not be higher or lower than 5.0

2.2. Input command

 After the relevant packages are imported, enter the package management console:

Execute the command to automatically generate entity classes (fill in your own database connection string):

Scaffold-DbContext "Data Source=.;Initial Catalog=DB_ERP;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

 The end result is this

2.3, Automatically generate and update the method of database entity class

When the project is later, the database is modified, and the entity class also needs to be updated.

Scaffold-DbContext "Data Source=.;Initial Catalog=DB_ERP;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model -Force 

Add -Force after the original command .

3. Supplement

After completing the above steps, when you run the interface, the following error may be reported:

System.InvalidOperationException: Unable to resolve service for type 'ERP.Models.DB_ERPContext' while attempting to activate 'ERP.Controllers.AddPuOrdersController'.

 Solution:

  1.  Find the entry into the Startup.cs file
  2. Add in the ConfigureServices method (fill in your database context ):
     services.AddTransient<DB_ERPContext>();

 If you have any questions, please private message or leave a message!

Guess you like

Origin blog.csdn.net/qq_56966336/article/details/124774605