2

please, how to work with enums in Entity Framework code first. i want that in my class "Annonce" i can have this proprety

public Status EtatAnnonce { get; set; } 

and Status is defined like this

public enum Status
{
    Pending,
    Approved
}
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
ucef
  • 557
  • 3
  • 10
  • 27
  • Check this, http://the--semicolon.blogspot.com/p/handling-enum-in-code-first-entity.html – iJay Aug 26 '14 at 10:12

4 Answers4

2

You need to create a converter field to store the value as int in the database.

public int MyEnumValueInt {get;set;}

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

Note: The enum support will be improved in EF 5.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
1

Will point you towards

EF5 does not create enum columns

To give a summary of enum support in Entity Framework code first:

EF4: Not supported

EF5: only supported if you are targeting .net framework 4.5 and higher

EF6: only supported if you target .net 4.0 and higher

Cheers!

Community
  • 1
  • 1
Adam Diament
  • 4,290
  • 3
  • 34
  • 55
0

I've answered two questions regarding Enums in EF; these should help you along:

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

and

EF 4.1 Code First - map enum wrapper as complex type

Community
  • 1
  • 1
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
0

You can use private properties in your model to map your data to whatever property type you want.

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

Then you just need to add the configuration to your OnModelCreating method

modelBuilder.Configurations.Add(new Piece.PieceConfig());
dss
  • 470
  • 5
  • 12