参考:
部分代码如下
public class AppDbContext:DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) :base(options)
{
}
public DbSet<Student> Student { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
foreach (var entity in builder.Model.GetEntityTypes())
{
// 覆写表名
//entity.SetTableName(entity.GetTableName());
// 覆写列名
foreach (var property in entity.GetProperties())
{
property.SetColumnName(property.GetColumnName().ToSnakeCase());
}
foreach (var key in entity.GetKeys())
{
key.SetName(key.GetName().ToSnakeCase());
}
foreach (var key in entity.GetForeignKeys())
{
key.SetConstraintName(key.GetConstraintName().ToSnakeCase());
}
foreach (var index in entity.GetIndexes())
{
index.SetDatabaseName(index.GetDatabaseName().ToSnakeCase());
}
}
}
}
//统一变成小写,属性className到数据库变成字段class_name,按需求调整代码
public static class StringExtensions
{
public static string ToSnakeCase(this string input)
{
if (string.IsNullOrEmpty(input)) { return input; }
return Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
}
}