/// <summary>
/// 自定义业务数据库上下文
/// </summary>
public class TestEFCoreDbContext : DbContext
{
#region 数据库实体集合,对应数据库表
/// <summary>
/// 实体集合
/// </summary>
public DbSet<MyEntity> MyEntitys { get; set; }
#endregion
/// <summary>
/// 构造方法
/// </summary>
public TestEFCoreDbContext(IConfiguration configuration)
{
//可以注入连接字符串等配置,后续使用
}
/// <summary>
/// 配置数据库连接字符串
/// </summary>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseSqlite(connectionString); //确定要使用的数据库及其连接字符串,可以从配置中注入
}
/// <summary>
/// 配置数据库表字段映射关系
/// </summary>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EngSolution>(entity =>
{
entity.ToTable("MyEntity").HasComment("EFCore演示demo实体"); //注释
entity.HasKey(x => x.Id);
entity.Property(x => x.Id).ValueGeneratedOnAdd(); //Id 自增,整型
entity.Property(x => x.Name).HasColumnType("nvarchar(64)").IsRequired().UseCollation("NOCASE"); //名称不区分大小写
entity.Property(x => x.Address).HasColumnType("nvarchar(128)"); //需要手动指定数据库表字段数据类型
entity.Property(x => x.Email).HasColumnType("nvarchar(32)").IsRequired(); //字符串类型若必填则需要显示指定
entity.Property(x => x.Price); //值类型则无需指定是否必填
entity.Property(x => x.EnumType).HasColumnType("nvarchar(32)").HasConversion<string>(); //#枚举或其它类型可以指定转换为字符串类型,枚举类型本身已支持,无需显示调用转换
});
}
}
Program.cs
//数据库组件
builder.Services.AddDbContext<TestEFCoreDbContext>();
//...
//...
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//业务数据库初始化,适合初期调试等频繁变动表结构情况,后续使用迁移
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<TestEFCoreDbContext>();
context.Database.EnsureCreated();
DbInitializer.Initialize(context);
}
//...