EF Core (EntityFramework Core) is an entity-relational mapping (O/RM) database access framework. The advantage of this mode is that developers can use the object model to operate the database, which is a more friendly way for developers.
Where is the O/RM brute force?
To operate the database in the non-object model, it is necessary to directly use the sql language to do a large number of CURD operations (Creat create; update update; read read; delete delete). These operations are cumbersome and error-prone to write, but the purpose is only to operate the database, not the business. The object model (O/RM) is based on business and uses its own programming language, which is equivalent to encapsulating the details of operating the database, allowing developers to concentrate on business. However, this mode is not perfect. If the focus of the business or the bottleneck is to operate the database, that is, to control the database in a refined manner, then the encapsulation is superfluous, no matter how good the encapsulation is.
1. Create the model
The following three "conventions" will generate models:
1. Dbset <model a>
2. The class model a{
list<model b>;
}
3. modelBuilder.Entity<model c>();
The [NotMapped] annotation feature can prevent the generated model from being mapped to the database.
Fluent API (flow api) can block mapping: modelBuilder.Ignore<blocked type>().
The priority of the three model controls is Fluent API > Annotation Features > Conventions
1.1 Model Internal Data
By default public properties with get;set; will be mapped.
1.1.1 Primary key
Attribute name ID or type name Id will be mapped as primary key.
[Key] Annotation property is set to key.
modelBuilder.Entity<model>().Haskey(c => c. property is set to key), this method can also set multiple keys.
1.1.2 Required attributes
The [Required] annotation attribute specifies that the attribute must provide a value when submitting to the database.
modelBuilder.Entity<model>().Property(b => b.Required property).IsRequired().
1.1.2 Data length
[MaxLength(500)]
modelBuilder.Entity<Model>().Property(b => b.Property).HasMaxLength(500);
1.1.3 Hidden properties
context.Entry(model).Property("Hidden property").CurrentValue = DateTime.Now;
1.2 Relationship
Principal entity
Dependent entity: Relatively speaking
Foreign key: An attribute that stores the principal key of an associated entity
Principal key: primary key or alternate key
Navigation properties (collection navigation properties, reference navigation properties, reverse navigation properties): properties defined with associated entity types
The [ForeignKey] annotation attribute is used on navigation properties to specify foreign keys
[InversePropery] Annotation property specifies an inverse navigation property
1.2.1 Fully Defined Relationships
The principal entity contains navigation properties that point to dependent entities; the dependent entities contain foreign keys and reverse navigation properties.
1.2.2 No foreign keys
Automatically generate hidden properties for foreign keys
1.2.3 Individual Navigation Properties
Only a single navigation property is required to confirm the relationship
1.3 Relational database modeling
[Table("table name")] table mapping
[Column("column name')] column mapping
2. Query data
.TOList() tracks (change) queries. Equivalent to R in CURD
.AsNoTracking().ToList() does not track (change) the query and is faster.
By default, if an entity is not returned (but only a subset of its properties) no tracking will be implemented.
.FromSql("SQL statement").ToList() executes the query in raw SQL.
3. Save data
.SaveChanges() saves (tracked) all changes.
.Add() is equivalent to C in CURD
Modify the attribute is equivalent to U
.Remove() is equivalent to D
The modified mode (CUD) can be automatically tracked for the changes of each record, and then the relevant CURD operations are performed. The programmer does not need to remember every change and carefully write SQL statements, which is the charm of O/RM.
4. Common databases
Microsoft.EntityFrameworkCore.SqlServer ms sql server
Microsoft.EntityFrameworkCore.Sqlite sqlite
MySql.Data.EntityFrameworkCore mysql
EntityFrameworkCore.Jet access
Npgsql.EntityFrameworkCore.PostgreSQL postgresql
5. Manage the database schema
To keep the EF Core model and database schema in sync, there are two ways:
Migrations: A synchronous approach that takes the EF Core model as the source
Reverse Engineering: Take the database schema as the source and synchronize to the ef core model
5.1 Migration
Generate migration preparation files:
PowerShell:
Add-Migration InitialCreate
Console:
dotnet ef migrations add InitialCreate
Update to database schema:
powershell: Update-Database
console: dotnet ef database update
Add new migration:
powershell: Add-Migration new migration project
console: dotnet ef migrations add new migration project
Delete migration:
powershell: Remove-Migration
console: dotnet ef migrations remove
Revert migration:
powershell: Update-Database migration project
console: dotnet ef database update migrate project
In-procedural method:
myDbContex.Database.Migrate() performs the migration.
EnsureCreated() will cause the migration to fail.
Ensuring the synchronization between the model and the database is a critical foundational work. On this basis, the operation of the model is meaningful and the simplicity is reflected.
During the development process, it is almost impossible not to modify the model once and for all, so master the synchronization tools.
5.2 Reverse Engineering
Scaffold-DbContext –Connection<string> –Provider <String> –OutputDir <string>