preface

I still remember that when I was learning database operation, I used ADO.NET to operate and query data step by step. I had to parse the queried data and then return it to the application layer. Faced with such repetitive and tedious work, there are always some gods or teams to encapsulate it, thus many ORM frameworks have emerged, allowing partners to focus more on business processing, and at the same time more object-oriented development, which is of great help to improve work efficiency.

At present, there are many ORM frameworks for C#, the most popular ones are FreeSql, SqlSugar, Dapper, EF/EF Core, linq2db, etc.

Of course, there are also some small partners to its performance comparison, each has advantages. From my personal use and that of my friends around, EF/EF Core and Dapper are relatively popular. Here is the FIRST talk about EF Core, later seize the opportunity to share other friends;

The body of the

With the rapid advance of.netcore, EF Core has followed suit. The current long-term support is EF Core3.1, and the next stable release, EF Core5.0, is planned to follow. The release of Net5 is expected this month (November 2020), so Microsoft is taking EF Core very seriously.

EF has three development modes: CodeFirst, ModelFirst and DbFirst. DbFirst and CodeFirst are more commonly used according to business needs and personal preferences. EF Core now recommends using CodeFirst for project development, or reverse engineering with database design first. Both are illustrated here;

CodeFirst is used in the project. The database used here is the NATIVE LocalDb of VS, and the project is still a WebApi project. Since the actual combat is getting started, it must have some appearance, so here is a simple imitation of the form of three-tier architecture for example demonstration, the following project structure:

Project dependencies are as follows:

  • The EFCoreTestDemo API project relies on the EFCoreTestModel and EFCoreTestService project;
  • The EFCoreTestService service layer project relies on the EFCoreTestModel and EFCoreTestRespository project.
  • The EFCoreTestRespository data layer relies on the EFCoreTestModel project

Structure good, now start knocking code, such as simulation user maintenance add, delete, change, check it; Since it’s CodeFirst, put the database aside for now. The following steps begin:

  1. Do user maintenance, must have a user entity, first add a user class in the Model layer;

  2. The next thing you need to do is add, delete, change, and check the data. If you’re using EF, you have to have a DbContext, which is related to data storage, so put it in the data layer.

  3. In fact, at this stage, I prefer to migrate first, to see if there is a problem, can normally generate the database and the corresponding table; (There’s no need to migrate and continue coding, but it’s a good idea to nip the problem in the bud);

    If you want to migrate, you must pass the connection string of the data to the WebApi project Startup.

    Where did the database connection string in the figure above come from? Did you write it yourself? Ha, ha, ha, ha, ha, ha, ha, ha, ha, copy from here, here incidentally created before the database deleted, convenient testing, as shown below:

    There are two modes of migration, one is in the form of command line and the other is in the package manager console (PMC) in VS.

    ** CLI: ** Dotnet tool install –global dotnet-ef is used to install the CLI tool

    Concentrated in the specified in the migration program to install Microsoft. EntityFrameworkCore. Design, migration will not succeed. The migration process is shown as follows:

    * * the package manager console (PMC) way to migrate: * * need to concentrate in the specified in the migration program to install Microsoft. EntityFrameworkCore. Tools package, otherwise the migration failed:

  4. Migration is ok, go back to the code logic; Now it is time to start editing the business code, that is, adding, deleting, changing and checking users. Start with the data layer, as shown in the figure below:

    The business layer:

    Controller:

    Using built-in dependency injection:

  5. The rest is to run and see the result, here does not inherit Swagger, use Postman tool to test, as shown below:

Through the above steps, the process from entity creation -> migration -> business writing using EF Core CodeFirst is basically like this. Repeat the above steps for additional entities. Finish the process, then talk about other technical points in the above process ↓↓↓

Add, delete, change and check operation

Add a user case, first wrap the original object, then mark the state of the wrapped object, and finally perform the unified operation through SaveChanges, as follows:

The same principle applies to user deletion and update as to user addition, as follows:

Query, usually through DbContext built-in methods, Lamda expressions, or Linq statements, can also find traceable wrapped objects, but the query can be set to untraceable. Sometimes, to improve performance, it can be set to:

Overall setting does not track:

The migration command

The above mentioned migration commands only add migration and update the database, there are some common commands are also more commonly used, as follows:

Usually, the generation environment will use the script to generate the database and table, then the development of the command is carried out, how to generate the corresponding script? The diagram below:

For the deleted migration scenario, it is generally not satisfied with the current migration, such as wrong fields, type misuse, etc., as follows:

As shown in the figure above, the new migration has been completed, but due to the incorrect Age type, this migration should be abandoned and migrated again. Of course, it cannot be deleted, but the subsequent query of historical migration records will cause misunderstanding. Delete the most recent migration as follows:

Table problem

The EF Core framework does not specify the column type that corresponds to the fields and Settings. The EF Core framework automatically generates the column type for us according to the default rules, which is very nice.

As shown in the above, the EF Core framework will be the default name of the class as a show that default to the maximum, the length of the string, if these are certainly not what we want, so the author must think of this, provides us with the modified method, the way we usually use annotations or FluentApi and change the form of constraints, annotations directly in the corresponding columns marked, However, FluentApi is generally recommended, which is relatively flexible. Write the corresponding code in OnModelCreating in DbContext as follows:

Then re-migrate and update to the database as follows:

Linq query

In EF, Linq can be used as an example of how to use the DbContext method and the Lamda expression. In EF, Linq can be used as an example of how to use the DbContext method and Lamda expression.

Does it look like SQL? Although Linq is a new syntax, it looks familiar and is easy to use. Here is not going to go into depth to say, just to small partners on a mouth; So heartless? Of course not. I have uploaded the Linq file collected before, for your reference:

Official documentation: docs.microsoft.com/zh-cn/dotne…

Collect documents:

Link: pan.baidu.com/s/1BZivBXG9…

Extraction code: 9qyu

Reverse engineering (database design first, then generate corresponding Model according to database)

For some projects, when the partners have received the hand of the database design, this situation is not necessary stubborn an entity knock, re generate the database, can be through the database reverse generation code, anyway how convenient how to; There is also a case that many friends prefer database first development mode, direct reverse engineering is good;

Create a test project with EF Core’s Core package and Design package installed as follows:

Also use the command line or package management console, here using the command line, execute the following command in the test project directory (here is essentially a, also need to install Microsoft EntityFrameworkCore. Essentially a 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
Copy the code

The above commands are briefly described:

Dotnet EF DBContext Scaffold specifies the database connection string.

The second parameter represents the Provider specified for the database and the Nuget package corresponding to the database.

-o: indicates the location where the generated entity class is stored.

–context: generated dbContext class name;

–context-dir: specifies the location of the generated dbContext;

-f: overwrites existing files.

-v: displays the migration process and error information.

-t: indicates the code for reverse table generation. If this code is not specified, all tables are generated.

-n: specifies the namespace to generate the class name. This is provided by EF Core5.0.

– context-namespace: specifies the namespace to generate DbContext. This is provided by EF Core5.0.

Note: The generated class and DbContext can be generated to the corresponding location according to the parameters to meet their own requirements.

If the MySql, you need to install Pomelo. EntityFrameworkCore. MySql package, other steps are the same, is not demonstrated here, I leave to the junior practice; Really don’t be too simple, only do it yourself, encounter problems, and then solve, finally can improve, experience.

conclusion

This is just a brief introduction to the use of EF Core, migration process and reverse engineering operation. Other advanced uses will be shared in a series of times, and friends can also improve themselves. I will share all the resources here. Speaking of which, the following file download address we can only talk about me in the public number, the first two blog because of the file download address, some blog platform put me banned, it is very embarrassing, but revised appeal.

Github address: github.com/zyq025/DotN…

A handsome guy who was made ugly by the program, pay attention to “Code variety circle “, identify attention to learn with me ~~~

Lu wen is not easy, don’t want white glance, three even go ~~~~