2

按照惯例,每个属性都将设置为映射到与该属性同名的列。如果我想更改默认映射策略,我可以使用 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; }
}

数据库很大,我不想将每个属性和类名映射到适当的数据库对象。是否有任何全局方式来定义这种类型的映射?

CustomerName -> CUSTOMER_NAME,CreditAmount -> CREDIT_AMOUNT 等等。

4

2 回答 2

2

使用反射进行该约定的可能方法是:从 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 上测试

于 2021-11-19T13:28:15.803 回答
0

您只需要从中迭代实体和属性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);
}
于 2021-11-19T13:46:28.863 回答