按照惯例,每个属性都将被设置为映射到与该属性同名的列。如果我想更改默认映射策略,我可以使用Fluent API或Data Annotation来完成。但是,我想为所有实体中的所有属性到数据库列设置一个自定义映射策略。我的数据库已经存在,列名像ID、CUSTOMER_NAME、CREDIT_AMOUNT等等,所以列名不遵循PascalCase表示法。所有对象名称都是大写的,单个单词用"_"符号分隔。整个数据库都是如此。我想把这个命名映射到这样一个类:
public class Payment
{
public int ID { set; get; }
public string CustomerName { get; set; }
public decimal CreditAmount { get; set; }
}
数据库很大,我不想将每个属性和类名映射到适当的数据库对象。有什么全局方法可以定义这种类型的映射吗?
客户名称->CUSTOMER_NAME,CreditAmount->CREDIT_AMOUNT等等。
使用这样的反射执行该约定的可能方法:从DbContext类的DBSet属性获取实体类型然后获取实体类型的属性(列(
所以在DbContext类中添加以下行:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//see below for this extension method
this.ApplyCaseMappingRule(modelBuilder);
base.OnModelCreating(modelBuilder);
}
扩展方法来源:
public static class Extensions
{
public static void ApplyCaseMappingRule<TDbContext>(this TDbContext _, ModelBuilder modelBuilder) where TDbContext:DbContext
{
var ignoreType = typeof(NotMappedAttribute);
var dbSetProps = typeof(TDbContext).GetProperties();
foreach (var dbSetProp in dbSetProps)
{
if (dbSetProp.PropertyType.TryGetEntityTypeFromDbSetType(out var entityType))
{
modelBuilder.Entity(entityType, option =>
{
option.ToTable(Mutate(dbSetProp.Name));
var props = entityType.GetProperties();
foreach (var prop in props)
{
//check if prop has Ignore attribute
var hasIgnoreAttribute =
prop.PropertyType.CustomAttributes.Any(x => x.AttributeType == ignoreType);
if (hasIgnoreAttribute) continue;
option.Property(prop.PropertyType, prop.Name).HasColumnName(Mutate(prop.Name));
}
});
}
}
}
private static bool TryGetEntityTypeFromDbSetType(this Type dbSetType, out Type entityType)
{
entityType = null;
if (dbSetType.Name != "DbSet`1") return false;
if (dbSetType.GenericTypeArguments.Length != 1) return false;
entityType = dbSetType.GenericTypeArguments[0];
return true;
}
public static IEnumerable<string> SplitCamelCase(this string source)
{
const string pattern = @"[A-Z][a-z]*|[a-z]+|d+";
var matches = Regex.Matches(source, pattern);
foreach (Match match in matches)
{
yield return match.Value;
}
}
public static string Mutate(string propName)
{
return string.Join("_", propName.SplitCamelCase().Select(x => x.ToUpperInvariant()));
}
使用EF 5.0.0 在.NET 5上进行测试
您只需要迭代modelBuilder.Model
中的实体和属性,例如
string ToDatabaseIdentifier(string propertyName)
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < propertyName.Length; i++)
{
var c = propertyName[i];
if (i>0 && Char.IsUpper(c) && Char.IsLower(propertyName[i-1]))
{
sb.Append('_');
}
sb.Append(Char.ToUpper(c));
}
return sb.ToString();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var e in modelBuilder.Model.GetEntityTypes())
{
e.SetTableName(ToDatabaseIdentifier(e.Name));
foreach (var p in e.GetProperties())
{
p.SetColumnName(ToDatabaseIdentifier(p.Name));
}
}
base.OnModelCreating(modelBuilder);
}