C ා data operation series - 5. Introduction to ef core

0. Preface

The previous chapter introduced the ORM framework briefly, and wrote a tool class similar to orm. This chapter will introduce the Core version of Entity Framework, a famous ORM framework in the C ා world.

The non Core version of Entity Framework has been updated to 6 generations, which is a proven ORM framework. Here is a brief introduction to the advantages of Entity Framework (EF for short, don't use this as a keyword search, or you will be fooled into an English training institution).

The design concept of C ා is that convention is superior to configuration, which means to avoid the use of configuration files or configuration codes through a certain degree of standardized formatting. EF can be said to be a good interpretation of this concept.

  • EF can automatically resolve the mapping between classes and tables without any configuration (the specific mapping logic is the same or similar to our handwritten ORM ORM tool class).
  • Automatically track changes. When using the elements obtained through EF directly, EF will automatically track which fields have changed. When calling and saving manually, EF will send the data back to the database.
  • It can delay loading required data, foreign key reference properties, query results, etc
  • Rich mapping relationships, support one-to-one, one to many, many to many, even inheritance, single table and multiple instances, etc
  • You can use Linq for queries
  • Non Core version can generate entity classes through database tables, and both can generate tables through entity classes
  • ADO.NET based database connection and can be used to connect to SQL Server, Oracle, MySQL, SQLite, PostgreSQL, DB2, etc

Of course, there is another feature: EF is better than configuration by convention, so EF can also be configured. EF can be configured using Fluent or profile.

After a lot of advantages of Entity Framework, let's start to use the Entity Framework Core.

Here is a brief introduction to the reasons for choosing Core. Microemulsion has been promoting cross platform strategy in recent years. Because EF is more developed based on. NET Framework, Microsoft made some modifications to. net core based on EF, and then EF Core was born. It can be said that EF Core is specially developed for. net core. And. net core has more and better development.

1. Entity Framework core installation

Now let's try to use the EntityFramework Core.

Create a new project first:

  • Visual Studio

    Click next to select the Console program:

    Click Create

  • Visual Studio Code

    dotnet new console -o ef_demo
    cd ef_demo

    Then open the ef? Demo directory with VS Code.

Then select the database:

This time, it's not the same as the previous selection. SQLite database is selected this time. This is a super small database, you can not install any additional software, as long as there is a file, and then through the code can access.

Next, add the SQLite package for EF:

In a non Visual Studio environment, you can install a three-party library using:

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

This command installs. This is the command of the dotnet command line to install the tripartite package. For Visual Studio or Rider, you can install the tripartite package through the graphical NuGet.

If NuGet's command line interface is used for installation, you can use:

Install-Package Microsoft.EntityFrameworkCore.Sqlite

This line of command installs the NuGet package.

2. Entry level usage

First, create two entity classes:

public class ModelA
	public int Id { get; set; }
	public string Name { get; set; }
	public List<ModelB> ModelBs { get; } = new List<ModelB>();
public class ModelB
    public int Id { get; set; }
    public string Name { get; set; }
    public int ModelAId { get; set; }
    public ModelA modelA { get; set; }

Then create an inheritance from


Context class for:

public class DefaultContext: DbContext
    public DbSet<ModelA> ModelAs { get; set; }
    public DbSet<ModelB> ModelBs { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=blogging.db");

Note that the connection string is set in the OnConfiguration method.

If you are using a database with existing data, you do not need to perform the following steps. Otherwise, it is recommended to perform the following steps so that the database can be generated by the tools provided by EF Core:

In NuGet's console interface, enter the following command:

Install-Package Microsoft.EntityFrameworkCore.Tools
Add-Migration InitialCreate

Or enter in the command line interface:

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

After successful execution, the following will be added to the root directory of the project:

This is the migration record reserved by EF Core for next use.

If the SQLite file blogging.db does not exist in the root directory of the project, the file will be created automatically and the table will be set at the same time; if there is, but not SQLite, an error will be reported.

Using the tool to connect to the blogging.db database, you can see the DDL of the table corresponding to the two entity classes automatically generated by EF:

    "Name" TEXT NULL,
-- auto-generated definition
create table ModelAs
    Id   INTEGER not null
        constraint PK_ModelAs
            primary key autoincrement,
    Name TEXT

Let's skip the relationship of automatic mapping and see how to use it:

var context = new DefaultContext();
//add to
context.Add(new ModelA { Id = 10, Name = "test" });
context.SaveChanges();//Save data to database
var modelA = context.ModelAs.Where(p => p.Id > 1).First();
//to update
modelA.Name += DateTime.Now;

Here is a simple demonstration of how to use it. So far, EF Core can meet the requirements of getting started development. Of course, EF is not the only one. The next article describes how to customize mapping relationships.

Please pay attention to more My blog Mr. Gao's Cabin

Tags: C# Database SQLite SQL Oracle

Posted on Thu, 14 May 2020 03:05:51 -0700 by rebelo