EF Core
1. Introduction
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology.
EF Core can serve as an object-relational mapper (O/RM), which:
Enables .NET developers to work with a database using .NET objects.
Eliminates the need for most of the data-access code that typically needs to be written.
EF Core supports many database engines, see Database Providers for details.
2. The model
With EF Core, data access is performed using a model.
2.1 Entity
public class Patient
{
/// <summary>
/// 患者ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 患者ID
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
/// 患者姓名
/// </summary>
public string PatientName { get; set; }
/// <summary>
/// 患者编号
/// </summary>
public string PatientCode { get; set; }
/// <summary>
/// 患者住址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 患者电话
/// </summary>
public string TEL { get; set; }
/// <summary>
/// 患者性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 患者年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime BirthDate { get; set; }
/// <summary>
/// 字符型出生日期
/// </summary>
public string StrBirthDate { get; set; }
/// <summary>
/// 患者头像
/// </summary>
public string Avatar { get; set; }
/// <summary>
/// 患者描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 删除标识
/// </summary>
public bool IsDelete { get; set; }
}
2.2 fluent API
Entity Framework Core uses a set of conventions to build a model based on the shape of your entity classes. You can specify additional configuration to supplement and/or override what was discovered by convention.
Configures the entity of type TEntity
public class PatientEntityTypeConfiguration : IEntityTypeConfiguration<Patient>
{
public void Configure(EntityTypeBuilder<Patient> builder)
{
builder.Property(b => b.Address).HasMaxLength(50);
builder.Property(b => b.Avatar).HasMaxLength(50);
builder.Property(b => b.Description).HasMaxLength(500);
builder.Property(b => b.PatientCode).HasMaxLength(50).IsRequired();
builder.Property(b => b.PatientName).HasMaxLength(50).IsRequired();
builder.Property(b => b.Sex).HasMaxLength(50);
builder.Property(b => b.StrBirthDate).HasMaxLength(50);
builder.Property(b => b.TEL).HasMaxLength(50);
}
}
2.3 DB Migration
Add-Migration note...
Update-Database
3. The DBContext
A context object that represents a session with the database. The context object allows querying and saving data.
configure the database (and other options) to be used for this context.
public class CBCTConnectDbContext : DbContext
{
public DbSet<Patient> PatientDS { get; set; }
public DbSet<RadiationField> RadiationFieldDS { get; set; }
public DbSet<TreatmentPlan> TreatmentPlanDS { get; set; }
private IConfiguration? configuration = null;
public CBCTConnectDbContext()
{
configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(configuration.GetConnectionString("Default"), new MySqlServerVersion(new Version(8, 0, 29))).LogTo(Console.WriteLine, LogLevel.Information);
}
}
4. Packages
4.1 Microsoft.EntityFrameworkCore.Design
4.2 Microsoft.EntityFrameworkCore.Core
4.3 Microsoft.EntityFrameworkCore.Tools
4.4 DB providers for MySQL
1) Pomelo.EntityFrameworkCore.MySql
2) MySql.EntityFrameworkCore
5. Querying,Saving data
how to query, add, modify, and remove data using your context and entity classes.
5.1 Add
using (var dbContext = new CBCTConnectDbContext())
{
for (int i = 0; i < 10; i++)
{
var patient = new Patient
{
Address = "BJ" + i.ToString(),
Age = 18 + i,
Avatar = "",
BirthDate = DateTime.Now,
Description = "desciption" + i.ToString(),
IsDelete = false,
PatientCode = "1000" + i.ToString(),
PatientName = "name" + i.ToString(),
Sex = "男",
StartDate = DateTime.Now,
StrBirthDate = DateTime.Now.ToString()
};
dbContext.Add(patient);
}
await dbContext.SaveChangesAsync();
5.2 Update
using (var context = new CBCTConnectDbContext())
{
var patient = context.PatientDS.First();
patient.PatientName = "hmpt@4503";
context.SaveChanges();
}
5.3 Delete
using (var context = new CBCTConnectDbContext())
{
var patient = context.PatientDS.First();
context.PatientDS.Remove(patient);
context.SaveChanges();
}
5.4 Query
using (var context = new CBCTConnectDbContext())
{
var patientList = context.PatientDS.Where( p => p.Id>5 );
foreach (var p in patientList)
{
Console.WriteLine("id:" + p.Id);
}
}
5.5 Pagination
IQueryable<Patient> patients = mydatabase.PatientDS.Include( p => p.TreatmentPlans ).IgnoreQueryFilters().OrderByDescending( a => a.Id);
//减一是因为要从零开始
var items = patients.Skip((pageindex - 1) * pageSize).Take(pageSize);
5.6 Global Query Filters
modelBuilder.Entity<Patient>()
.HasQueryFilter(p => !p.IsDelete );
6. EF Core Framework
浙公网安备 33010602011771号