8

我有一个项目使用最新版本的 EF CF 和 PostgreSQL 和 Npgsql。

我的模型看起来像:

[Table("mytable")]
public class MyTable
{
    [Column("id")]
    public int Id { get; set; }
    [Column("mycolumn")]
    public string MyColumn { get; set; }
}

并且数据库/表/列具有小写名称,例如:

CREATE TABLE mytable
{
    id serial,
    mycolumn character(50)
}

Npgsql 生成带引号的 SQL 命令,因此由于 PostgreSQL 的特性,我必须使用数据注释,这很烦人。但是我不想在数据库中使用引号分隔的名称。

有没有办法将 Npgsql 配置为在生成命令时不包含引号或在生成的 SQL 中强制使用小写表/列名称?

4

2 回答 2

8

如果我没有遗漏什么 - 你想要一些通用的方法of changing the naming convention for tables吗?

EF6 有这个custom conventions功能 - 它仍然不是官方版本,但如果它适合你,一些链接......

http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions

在你的情况下,你必须为类/Type我猜实现它 - 例如(一些伪代码)......

1)实施IConfigurationConvention<Type, EntityTypeConfiguration>(您可以检查EF源EntityConventionBase

2) 在Apply- 更改通过配置 ( ToTable()) 生成表名称的方式 - 类似于.ToLowerCase()

3)添加到约定...

例如...

public class SmallCapsEntitiesConfigurationConvention
    : IConfigurationConvention<Type, EntityTypeConfiguration>
{
    public void Apply(Type memberInfo, Func<EntityTypeConfiguration> configuration)
    {
        configuration().ToTable(memberInfo.Name.ToLowerInvariant(), null);
    }
}

你可以在这里看到一个例子
http://blog.cincura.net/233167-custom-conventions-in-entity-framework-6-helping-firebird/

否则,我不知道Npgsql/ PostgreSQL - 它对我来说确实有点“原始”。但是你可以在 EF 端处理它。

于 2013-04-04T15:36:04.897 回答
1

这是 EF Core 的示例。

当前代码转换tables,properties和为 蛇形大小写keys,您可以将其用作自定义约定的基础:indexesPostgre

using System;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Npgsql;

namespace Database.Customization
{
    public class PostgreDbContext : DbContext
    {
        private static readonly Regex _keysRegex = new Regex("^(PK|FK|IX)_", RegexOptions.Compiled);

        public PostgreDbContext(DbContextOptions options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            FixSnakeCaseNames(modelBuilder);
        }

        private void FixSnakeCaseNames(ModelBuilder modelBuilder)
        {
            var mapper = new NpgsqlSnakeCaseNameTranslator();
            foreach (var table in modelBuilder.Model.GetEntityTypes())
            {
                ConvertToSnake(mapper, table);
                foreach (var property in table.GetProperties())
                {
                    ConvertToSnake(mapper, property);
                }

                foreach (var primaryKey in table.GetKeys())
                {
                    ConvertToSnake(mapper, primaryKey);
                }

                foreach (var foreignKey in table.GetForeignKeys())
                {
                    ConvertToSnake(mapper, foreignKey);
                }

                foreach (var indexKey in table.GetIndexes())
                {
                    ConvertToSnake(mapper, indexKey);
                }
            }
        }

        private void ConvertToSnake(INpgsqlNameTranslator mapper, object entity)
        {
            switch (entity)
            {
                case IMutableEntityType table:
                    var relationalTable = table.Relational();
                    relationalTable.TableName = ConvertGeneralToSnake(mapper, relationalTable.TableName);
                    if (relationalTable.TableName.StartsWith("asp_net_"))
                    {
                        relationalTable.TableName = relationalTable.TableName.Replace("asp_net_", string.Empty);
                        relationalTable.Schema = "identity";
                    }

                    break;
                case IMutableProperty property:
                    property.Relational().ColumnName = ConvertGeneralToSnake(mapper, property.Relational().ColumnName);
                    break;
                case IMutableKey primaryKey:
                    primaryKey.Relational().Name = ConvertKeyToSnake(mapper, primaryKey.Relational().Name);
                    break;
                case IMutableForeignKey foreignKey:
                    foreignKey.Relational().Name = ConvertKeyToSnake(mapper, foreignKey.Relational().Name);
                    break;
                case IMutableIndex indexKey:
                    indexKey.Relational().Name = ConvertKeyToSnake(mapper, indexKey.Relational().Name);
                    break;
                default:
                    throw new NotImplementedException("Unexpected type was provided to snake case converter");
            }
        }

        private string ConvertKeyToSnake(INpgsqlNameTranslator mapper, string keyName) =>
            ConvertGeneralToSnake(mapper, _keysRegex.Replace(keyName, match => match.Value.ToLower()));

        private string ConvertGeneralToSnake(INpgsqlNameTranslator mapper, string entityName) =>
            mapper.TranslateMemberName(ModifyNameBeforeConvertion(mapper, entityName));

        protected virtual string ModifyNameBeforeConvertion(INpgsqlNameTranslator mapper, string entityName) => entityName;
    }
}

更新:

如果您使用的是 EF 核心 3,那么Relational()将导致错误,因为该方法最近已被删除。修改ConvertToSnake函数定义如下:

private void ConvertToSnake(INpgsqlNameTranslator mapper, object entity)
{
        switch (entity)
        {
            case IMutableEntityType table:
                table.SetTableName(ConvertGeneralToSnake(mapper, table.GetTableName()));
                if (table.GetTableName().StartsWith("asp_net_"))
                {
                    table.SetTableName(table.GetTableName().Replace("asp_net_", string.Empty));
                    table.SetSchema("identity");
                }

            break;
        case IMutableProperty property:
            property.SetColumnName(ConvertGeneralToSnake(mapper, property.GetColumnName()));
            break;
        case IMutableKey primaryKey:
            primaryKey.SetName(ConvertKeyToSnake(mapper, primaryKey.GetName()));
            break;
        case IMutableForeignKey foreignKey:
            foreignKey.SetConstraintName(ConvertKeyToSnake(mapper, foreignKey.GetConstraintName()));
            break;
        case IMutableIndex indexKey:
            indexKey.SetName(ConvertKeyToSnake(mapper, indexKey.GetName()));
            break;
        default:
            throw new NotImplementedException("Unexpected type was provided to snake case converter");
    }
}
于 2018-03-26T10:07:45.707 回答