c# - Entity Framework 代码优先和 Firebird - 外键名称问题

标签 c# database entity-framework firebird

我正在尝试使用 EF 代码优先和这个简单的代码创建包含 2 个表(DistrictsDatabases)的新数据库:

using (var db = new FirebirdDBContext(_connectionString))
{
    db.Database.CreateIfNotExists();
}

我的类(class):

public class District
{
    [Key]
    public int District_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string District_name { get; set; }

    [ForeignKey("DataBase")]
    public int DataBase_id { get; set; }

    public DataBase DataBase { get; set; }
}

public class DataBase
{
    [Key]
    public int DataBase_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string DataBase_name { get; set; }

    public ICollection<District> District { get; set; }

    public DataBase()
    {
        District = new List<District>();
    }
}    

但不幸的是它抛出了一个错误:

Specified argument was out of the range of valid values.
Parameter name: The name 'FK_Districts_DataBases_DataBase_id' is longer than Firebird's 31 characters limit for object names.

我知道 Firebird 的 31 个字符限制,但如果我先使用 Entity Framework 代码,我该如何解决这个问题?

最佳答案

增加 Firebird 对元数据字段名称的 31 个字符限制一直是一个不变的功能请求,并且没有增加长度限制的真正方法。

话虽如此,我们也许能够控制 EF 试图生成的外键约束名称的长度。这将涉及将您的类属性重命名为较短的名称(但仍将它们映射到它们的真实列名字)

希望 EF 根据类的属性名称而不是实际的列生成外键约束名称。

FK_Districts_DataBases_DataBase_id 是 23 + 11 = 34 个字符。 我们需要让它少于 32 个字符..

我认为这个前缀可能是不可避免的。 FK_Districts_DataBases_ 所以我们有 7-8 个字符后缀的余地。

试试这个:

public class District
{
    [Key]
    public int District_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string District_name { get; set; }

    [ForeignKey("DataBase")]
    [Column("DataBase_id")]
    public int DbId { get; set; } // reduce the column name

    public DataBase DataBase { get; set; }
}

public class DataBase
{
    [Key]
    [Column("DataBase_id")]
    public int DbId { get; set; } // reduce the column name

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string DataBase_name { get; set; }    

    public ICollection<District> District { get; set; }

    public DataBase()
    {
        District = new List<District>();
    }
} 

希望 EF 将约束名称设为“FK_Districts_DataBases_DbId”(27 个字符)

关于c# - Entity Framework 代码优先和 Firebird - 外键名称问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35789394/

相关文章:

c# - 如何在每次方法调用后隐式调用方法?

c# - 如何将 .NET 日期转换为 NSTimeInterval?

c# - 滚动 DataGridView 的合并标题单元格时出现问题

C# linq 更改构造函数无法添加新值

C# Entity Framework 核心端点 JWT 身份验证

c# - 如何反序列化 XML 中特定元素中属性的特定值?

Java线程安全的数据库连接

database - 如何使用 PostgreSQL 限制特定表中的行数?

mysql - 内部查询 case 表达式中的外部查询列

entity-framework - 在辅助角色中缓存域对象