c# - 在 OnModelCreating 期间设置列名称

标签 c# entity-framework-core

问题

我目前正在尝试通过设置的属性为我的表及其列添加前缀。我正在使用 Entity Framework 核心。我已经正确地为表名添加了前缀,但我似乎无法弄清楚列的前缀。我有一种感觉,我需要使用反射。

我已经留下了我的(可能很糟糕的)反射(reflection)尝试。有人有办法在实体中设置列的名称吗?


代码

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    Debugger.Launch();
    //Loop though each entity to set table names correctly
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        //Get the custom attributes of the entity
        var attributes = entity.ClrType.GetCustomAttributes(true);
        //Throw exception if there isn't any custom attribute applied to the class
        if (attributes.Length == 0)
            throw new ArgumentNullException(nameof(entity), "Entity is missing table prefix.");

        //Get the table prefix
        var prefix = attributes[0];

        //Set the table name
        entity.Relational().TableName = prefix + entity.Relational().TableName;

        //Loop through all the columns and apply the prefix
        foreach (var prop in entity.GetProperties())
        {
            var propInfo = entity.ClrType.GetProperty(prop.Name);
            propInfo.SetValue(entity.ClrType, prefix + prop.Name, null);
        }
    }
}

最佳答案

这与您对表名称所做的类似。只需使用 Relational() IMutablePropertyColumnName 的扩展方法属性:

foreach (var prop in entity.GetProperties())
{
    prop.Relational().ColumnName = prefix + prop.Relational().ColumnName;
}

关于c# - 在 OnModelCreating 期间设置列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55452732/

相关文章:

c# - 在 sql server 中调用 Web 服务

c# - EFCore 和 C# 中聚合之间的 DDD 和引用

c# - 在 docker 容器中包含 Entity Framework 工具

c# - 使用 Entity Framework Core、npgsql、PostgreSQL 创建新数据库

c# - Include() 上的 EF Core HasQueryFilter

c# - EntityFramework Core 自动生成键 id 属性

具有多种类型的 C# 泛型类型推断

c# - 创建简单的 c++.net 包装器。一步步

c# - 字符/字符串比较

c# - 使用非 VB6 对象在 VS2008 中调试 VB6