Asp-Net-Core開發(fā)筆記:EFCore統(tǒng)一實體和屬性命名風格
1前言
C# 編碼規(guī)范中,類和屬性都是大寫駝峰命名風格(PascalCase / UpperCamelCase),而在數(shù)據(jù)庫中我們往往使用小寫蛇形命名(snake_case),在默認情況下,EFCore會把原始的類名和屬性名直接映射到數(shù)據(jù)庫,這不符合數(shù)據(jù)庫的命名規(guī)范。
為了符合命名規(guī)范,而且也為了看起來更舒服,需要自己做命名轉(zhuǎn)換處理。
2FreeSQL的命名轉(zhuǎn)換功能
FreeSQL 內(nèi)置了很方便的命名風格轉(zhuǎn)換功能,只需要設(shè)置 UseNameConvert 就可以實現(xiàn) Pasca Case 到 snake_case 的轉(zhuǎn)換。
var fsql = new FreeSqlBuilder()
.UseConnectionString(DataType.MySql, Default.Value)
.UseAutoSyncStructure(true)
.UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
EFCore 沒有內(nèi)置這個功能,需要我們自行實現(xiàn)。
3使用正則實現(xiàn)命名風格轉(zhuǎn)換
使用正則表達式可以實現(xiàn)這個功能
這里來寫一個擴展方法
public static class StringExt {
public static string ToSnakeCase(this string input) {
if (string.IsNullOrEmpty(input)) {
return input;
}
var startUnderscores = Regex.Match(input, @"^_+");
return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
}
}
這個方法會在每個小寫字母/數(shù)字與大寫字母之間添加下劃線,并把整個字符串轉(zhuǎn)換為小寫。
4修改 EFCore 行為
EFCore 有非常豐富的功能,修改表名和字段名當然也不在話下。
重寫 DbContext 的 OnModelCreating 方法就行
public class AppDbContext : DbContext {
// ...
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
// CamelCase to SnakeCase
foreach (var entity in modelBuilder.Model.GetEntityTypes()) {
// Replace table names
if (!string.IsNullOrWhiteSpace(entity.GetTableName())) {
entity.SetTableName(entity.GetTableName()!.ToSnakeCase());
}
// Replace column names
foreach (var property in entity.GetProperties()) {
property.SetColumnName(property.GetColumnName().ToSnakeCase());
}
foreach (var key in entity.GetKeys()) {
if (!string.IsNullOrWhiteSpace(key.GetName())) {
key.SetName(key.GetName()!.ToSnakeCase());
}
}
foreach (var key in entity.GetForeignKeys()) {
if (!string.IsNullOrWhiteSpace(key.GetConstraintName())) {
key.SetConstraintName(key.GetConstraintName()!.ToSnakeCase());
}
}
foreach (var index in entity.GetIndexes()) {
if (!string.IsNullOrWhiteSpace(index.GetDatabaseName())) {
index.SetDatabaseName(index.GetDatabaseName()!.ToSnakeCase());
}
}
}
}
}
以上代碼會對表名、列名、key、index的名稱做轉(zhuǎn)換。
搞定~
5參考資料
-
https://andrewlock.net/customising-asp-net-core-identity-ef-core-naming-conventions-for-postgresql/
評論
圖片
表情
