Preface
Remember when I learned how to operate a database , use ADO.NET Data operation and query step by step , For the query data has to be parsed , The encapsulation is then returned to the application layer ; Encounter this kind of repetitive and tedious work , There are always some great gods or teams that encapsulate it , So a lot of ORM frame , Let small partners put more energy on business processing , At the same time, more program oriented object development , It's very helpful to improve work efficiency .
Currently on C# There's a lot of ORM frame , The more popular ones are probably FreeSql ( At home )、SqlSugar ( At home )、Dapper ( Abroad )、EF/EF Core ( Abroad )、linq2db ( Abroad ) etc. ,
Of course, there are also some small partners to compare its performance , Each has its own advantages . From my personal and the use of small partners around me ,EF/EF Core and Dapper The utilization rate is relatively high . Let's talk about EF Core, Take the opportunity to share other things with your partner ;
Text
With .NetCore The rapid advance of ,EF Core And keep up with it . The current long-term support version is EF Core3.1, And the next stable version EF Core5.0 Follow the plan with .Net5 Release together , It's expected to be this month (2020 year 11 month ), It can be seen that Microsoft's attitude towards EF Core It's very important ;
For those who have used it before EF Little buddy , We should all know ,EF There are three development models :CodeFirst、ModelFirst、DbFirst, These three types are used more according to business needs and personal preferences DbFirst and CodeFirst; Now? EF Core Recommended CodeFirst The way of project development , Of course, it can also be done through reverse engineering , Database design first . There will be examples of these two ways ;
Used in projects CodeFirst The way , The database used here is VS Self contained LocalDb, The project is still the old rule , One WebApi project ; Now that you're an introduction to actual combat , It's got to be something , So here is a simple imitation of the form of the three-tier architecture for example demonstration , The following project structure :
The project depends on :
- EFCoreTestDemo API Project dependence EFCoreTestModel and EFCoreTestService project ;
- EFCoreTestService The service layer project depends on EFCoreTestModel and EFCoreTestRespository project ;
- EFCoreTestRespository The data layer depends on EFCoreTestModel project
The structure is good , Now start typing code , For example, simulate the addition, deletion, modification and query of user maintenance ; Since it is CodeFirst, Put the database aside for a while . Start with the following steps :
-
Do user maintenance , There must be user entities , First in Model Add a user class to the layer ;
-
The next step is to manipulate the data , It's called adding, deleting, modifying and checking , Since we use EF, There must be one DbContext, This is about data storage , So put it in the data layer ;
-
In fact, at this stage , I prefer to move first , See if there's a problem , Whether the database and corresponding tables can be generated normally ;( In fact, there is no need to move here in a hurry , Continue coding , But it's a good idea to nip the problem in the cradle in advance );
Since we're moving , Must pass the connection string of the data , From here WebApi Project Startup When registering a service in the , And specify the migration program as WebApi project :
Where does the database connection string come from , Did you write it yourself ? Ha ha ha , Copy it , By the way, delete all the databases created before , Convenient test , Here's the picture :
There are two ways to migrate , One is the command line form , The other is in VS Package manager console in (PMC) Conduct ;
Command line mode : Need to install command line tools , The global installation method is used here , Following commands :dotnet tool install --global dotnet-ef
Install... In the specified migration assembly Microsoft.EntityFrameworkCore.Design, Otherwise the migration will not succeed . The migration process is as follows :
Package manager console (PMC) How to migrate : You need to install... In the specified migration assembly Microsoft.EntityFrameworkCore.Tools package , Otherwise the migration fails :
-
Migration is OK , Go back to code logic ; Now it's time to start editing business code , That is to add, delete, modify and query users , Let's start with the data layer , The specific steps are shown in the figure below :
The business layer :
controller :
Use built-in dependency injection :
-
The rest is to run and see the results , There is no inheritance here Swagger, Use Postman Tools to test , Here's the picture :
Go through the above steps , Use EF Core Of CodeFirst From creating entities -> transfer -> Finally, the process of business writing is basically like this ; If a new entity is added later , Or repeat the above steps . Finish the process , Let's talk about the other technical points in the above process ↓↓↓
Add, delete, change and check operation
Add user stories , First, wrap the original object , And then by identifying the state of the wrapper object , Finally through SaveChanges To perform a unified execution operation , as follows :
User deletion 、 Update and add the same reason , as follows :
Inquire about , Usually by DbContext Their own way 、Lamda expression , or Linq sentence , Also find traceable packaging objects , But you can make its queries untraceable , Sometimes to improve performance , Will be set or set up as a whole for :
The overall setting does not track :
Migration command
The migration commands mentioned above only add new migration and update database , There are also some commonly used instructions , as follows :
Usually , In the generation environment, the database and table are usually generated by script , It was developed by command , How to generate the corresponding script ? Here's the picture :
For delete migration scenarios , It's usually not satisfied with the current migration , For example, the field is wrongly written 、 Type misuse, etc , as follows :
Pictured above , The new migration is complete , But because of Age The type used is wrong , To abandon this migration , Re migrate , Of course, you can't delete , However, there will be misunderstandings when querying historical migration records . Delete the last migration as follows , as follows :
Table problem
In the process of the above migration , It does not specify the column type corresponding to the fields and settings , yes EF Core The framework follows the default rules , It's generated for us automatically , Is it very intimate , But since it's default , The framework certainly doesn't know what we need , The table generated below :
As shown in the figure above ,EF Core By default, the framework uses the class name as an indication , The length of the generated string is the maximum by default , These are certainly not what we want , So the author must have thought of this , It gives us a way to modify , We usually use annotations or FluentApi In the form of constraints and changes , The annotation is marked directly on the corresponding column , But it is generally recommended to use FluentApi, Relatively flexible ; stay DbContext Medium OnModelCreating Write the corresponding code in , as follows :
Then migrate and update to the database , as follows :
Linq Inquire about
stay EF In the process of use ,Linq It should be indispensable , It is estimated that some partners will say , Direct use DbContext The method and Lamda The expression will do , yes , That must be OK , It can only be said that the essence has not been used yet , Ha ha ha , Code programming oriented SQL Query statement , It's very convenient to use , as follows :
Does it look like SQL, Although it is Linq New syntax , But it's not strange to look at , It's also very convenient to use ; I'm not going to go into this , Just a word to my friends ; So heartless ? Of course not , I've collected the data before Linq The document has been uploaded , Friends can refer to :
Official documents :https://docs.microsoft.com/zh-cn/dotnet/csharp/linq/
Collect documents :
link :https://pan.baidu.com/s/1BZivBXG9WT-gOqsXKG08Ng
Extraction code :9qyu
Reverse Engineering ( First there's database design , And then generate the corresponding from the database Model)
For some projects , When the partners got it, they had designed the database , In this case, there is no need to insist on one entity at a time , Regenerate the database , You can generate code in reverse through the database , Anyway, you can come as convenient as you like ; There is also a case that many partners still prefer the database first development mode , Just reverse engineer ;
Here we use the data we created earlier and User surface , And then we built a test project , There's only... Installed in it EF Core The core package and Design package , as follows :
Also use the command line or the package management console , Here's the command line , stay test Execute the following command in the project directory ( Here is SqlServer, It also needs to be installed Microsoft.EntityFrameworkCore.SqlServer package ):
dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EFCoreTest1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" "Microsoft.EntityFrameworkCore.SqlServer" -o ./Models --context EFCoreTestContext --context-dir ./ -f
The above command simply states :
dotnet ef dbcontext scaffold The database connection string is specified later ;
The second parameter represents that it is specified by the corresponding database Provider, And the corresponding database Nuget package ;
-o: Represents the location where the generated entity class is stored ;
--context: Generated dbContext Class name of ;
--context-dir: Specify the generated dbContext Storage location ;
-f: Overlay existing files ;
-v: Display migration process and error information ;
-t: Specify table reverse generation code , If not specified, all tables are generated ;
-n: Specifies the namespace to generate the class name , This EF Core5.0 Provide ;
—context-namespace: Specify generation DbContext The namespace of , This EF Core5.0 Provide ;
notes : Generated classes and DbContext It can be generated to the corresponding position according to the parameters , Meet your own needs .
If it is MySql, Need to install Pomelo.EntityFrameworkCore.MySql package , The other steps are the same , I'm not going to do that here , Let's leave it to the kids to practice ; Really don't be too simple , It's only done by hand , Have a problem , And solve it , In the end, you can improve , Personal experience .
summary
Here's just a brief talk about EF Core Use , Migration process and reverse engineering operation sharing , Other advanced uses will be shared , Partners can also strengthen themselves , I have resources here , Will share ; Speaking of this , Follow up file download address, you can only chat with me in official account , For the first two articles, the download address is , Some blogging platforms have banned me from speaking , It's embarrassing , But the appeal has been amended .
Bowen source code github Address :https://github.com/zyq025/DotNetCoreStudyDemo
A handsome guy made ugly by the program , Focus on "Code Variety industry ", Identify, focus and learn from me ~~~
It's not easy to write , Don't look in vain , Three companies walk up ~~~~