【问题标题】:enums in EF code first首先在 EF 代码中枚举
【发布时间】:2012-04-12 09:52:17
【问题描述】:

请先了解如何在实体框架代码中使用枚举。我希望在我的课堂“Annonce”中我可以拥有这个属性

public Status EtatAnnonce { get; set; } 

而Status是这样定义的

public enum Status
{
    Pending,
    Approved
}

【问题讨论】:

标签: entity-framework-4 enums code-first


【解决方案1】:

您需要创建一个转换器字段以将值作为 int 存储在数据库中。

public int MyEnumValueInt {get;set;}

[NotMapped]
public MyEnum MyEnumValue
{
    get{ return (MyEnum)MyEnumValueInt;
    set{ MyEnumValueInt = (int)value;
}

注意:枚举支持将在 EF 5 中得到改进。

【讨论】:

    【解决方案2】:

    会指引你走向

    EF5 does not create enum columns

    先总结一下Entity Framework代码中对枚举的支持:

    EF4:不支持

    EF5:仅当您面向 .net 框架 4.5 及更高版本时才支持

    EF6:仅当您面向 .net 4.0 及更高版本时才支持

    干杯!

    【讨论】:

      【解决方案3】:

      我已经回答了关于 EF 中的枚举的两个问题;这些应该可以帮助您:

      Enums with EF code-first - standard method to seeding DB and then using?

      和

      EF 4.1 Code First - map enum wrapper as complex type

      【讨论】:

        【解决方案4】:

        您可以在模型中使用私有属性将数据映射到您想要的任何属性类型。

        // Model
        public class Piece
        {
        
            // Subclass Piece to add mappings for private properties
            public class PieceConfig : EntityTypeConfiguration<Piece>
            {
                public PieceConfig()
                {
                    Property(b => b.dbtype); // needed for EF to see the private property
                }
            }
        
            [Column("type", TypeName = "VARCHAR")]
            private string dbtype { get; set; }
        
            [NotMapped]
            public PIECE type
            {
                get { return (PIECE)Enum.Parse(typeof(PIECE), dbtype); }
                set { dbtype= value.ToString(); }
            }
        }
        

        那么你只需要将配置添加到你的 OnModelCreating 方法中

        modelBuilder.Configurations.Add(new Piece.PieceConfig());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-14
          • 1970-01-01
          • 2013-05-16
          • 2023-04-05
          • 1970-01-01
          • 2012-01-04
          • 1970-01-01
          相关资源
          最近更新 更多