Code First创建int而不是enum

问题描述 投票:2回答:1

我想创建一个名为'type'的枚举类型列,但是当我对我的Code First生成的DB进行反向工程时,它会将其指定为'int'。

enter image description here

这是我的Enum课程:

[Flags]
public enum TypeNames
{
    Een = 0,
    Twee = 1,
    Drie = 2
}

这是我的Grounds类,用'TypeNames'-enum创建表。 Properties类是另一个表(Grounds - Properties具有TPT继承)。

[Table("gronden")]
public partial class Grounds : Properties
{
    [Column("opp")]
    public double? Surface { get; set; }
    [EnumDataType(typeof(TypeNames)), Column("type")]
    public TypeNames Types { get; set; }
}

有什么想法,我在这里缺少一个枚举类型到我的数据库?

entity-framework enums ef-code-first
1个回答
0
投票

根据以下答案,似乎EnumDataTypeAttribute仅针对ASP.NET UI组件实现,而不是针对EF使用。 Should the EnumDataTypeAttribute work correctly in .NET 4.0 using Entity Framework?

EF Core 2.1实现了一项新功能,允许将Enums存储为数据库中的字符串。这允许数据自我描述,这对于长期可维护性非常有用。对于您的具体情况,您可以简单地做:

[Table("gronden")]
public partial class Grounds : Properties
{
    [Column("opp")]
    public double? Surface { get; set; }
    [Column("type", TypeName = "nvarchar(24)")]
    public TypeNames Types { get; set; }
}

您可以在此页面找到更多详细信息:https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions

另外,我注意到你在枚举上设置了FlagsAttribute。您是否希望能够将多个枚举值应用于单个实体?当值作为int持久化时,这应该可以正常工作,但如果存储为MySQL ENUM或字符串数​​据类型则不起作用。 MySQL确实支持SET数据类型,但EF似乎不太可能添加对此功能的支持,因为大多数其他数据库没有类似的概念。 https://dev.mysql.com/doc/refman/5.6/en/constraint-enum.html

如果您确实希望允许将多个枚举值应用于每个实体(类似于Stack Overflow上使用的标记的方式),您可以考虑创建多对多关系。基本上,这意味着将TypeNames枚举转换为数据库中的Types表,并允许EF生成GroundTypes表以将它们链接在一起。这是一个教程:http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

© www.soinside.com 2019 - 2024. All rights reserved.