2012-04-12 129 views
2

請問,如何先在Entity Framework代碼中使用枚舉。我想,在我的課「Annonce」我能有這個proprety首先在EF代碼中枚舉

public Status EtatAnnonce { get; set; } 

和狀態的定義如下

public enum Status 
{ 
    Pending, 
    Approved 
} 
+0

選中此項, http://the-semicolon.blogspot.com/p/handling-enum-in-code-first-entity.html – iJay 2014-08-26 10:12:54

回答

2

您需要創建一個轉換器字段的值存儲爲int類型的數據庫。

public int MyEnumValueInt {get;set;} 

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

注:支持ENUM將在EF 5

0

您可以在模型中使用的專用屬性將數據映射到任何你想要的屬性類型。

// 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()); 
1

會爲您指出

EF5 does not create enum columns

舉的枚舉支持實體框架代碼摘要第一個:

EF4:不支持orted

EF5:如果你是針對.NET框架4.5和更高

EF6僅支持:只有當你面向.NET 4.0和更高

乾杯支持!