一、环境依赖
安装环境: .Net 6
安装EF: dotnet tool install --global dotnet-ef 参考:EF Core 工具参考 (.NET CLI) - EF Core | Microsoft Learn
二、主要包说明
Microsoft.EntityFrameworkCore.Tools //安装后可以在包管理命令行使用add-migration和update-database等命令
Microsoft.EntityFrameworkCore.Design //EF命令行(CLI)工具
Microsoft.EntityFrameworkCore.Relational //安装后可以使用DbContext.Database.Migrate()方法,实现自动迁移
Microsoft.EntityFrameworkCore.Sqlite //为了轻量演示,这里使用sqlite演示
三、创建DbContext
public class SqliteDbContext : DbContext
{
private readonly string _connectionString = "Data Source=./local.db";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(_connectionString);
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//通过反射,避免反复添加DbSet,使用时通过DbContext.Set<T>获取指定DbSet
var assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.ExportedTypes)
{
if (type.IsClass && type != typeof(BaseEntity) && typeof(BaseEntity).IsAssignableFrom(type))
{
var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();
if (method != null)
{
method = method.MakeGenericMethod(new Type[] { type });
method.Invoke(modelBuilder, null);
}
}
}
base.OnModelCreating(modelBuilder);
}
}
四、CodeFirst模型类
public class BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
[Table("test_detail")]
public class TestDetail : BaseEntity
{
[Column("name")]
public string? Name { get; set; }
[Column("create_time")]
public DateTime? CreateTime { get; set; }
[Column("update_time")]
public DateTime? UpdateTime { get; set; }
}
五、生成迁移文件
//每次模型修改,需手动生成迁移文件
包管理器命令行:add-migration 20240718
六、运行实例
//.Net 6控制台程序
static async Task Main(string[] args)
{
var db = new SqliteDbContext();
db.Database.Migrate();
var detail = db.Set<TestDetail>();
var item = new TestDetail { Name = "张三" }
var exist_item = detail.Where(x => x.Name == item.Name).FirstOrDefault();
if (exist_item != null)
{
exist_item.Name = item.Name;
exist_item.UpdateTime = DateTime.Now;
detail.Update(exist_item);
}
else
{
item.CreateTime = DateTime.Now;
detail.Add(item);
}
db.SaveChanges();
}