Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use entity-framework to map int column to enum property

I have a enum type called Operation like this:

[Flags]
public enum Operation
{
    None = 0,
    View = (1 << 0),
    Add = (1 << 1),
    Edit = (1 << 2),
    Delete = (1 << 3),
    ReservedA = (1 << 4),
    ReservedB = (1 << 5),
    Admin = (View | Add | Edit | Delete)
}

and table permission contains a operations column. This table maps to a class like this:

[Table("rolepermission")]
public class Permission : IComparable
{
    private int _id = 0;

    private Operation _operations = Operation.None;

    private List<UserRole> _roles = null;

    public Permission()
    {
        _roles = new List<UserRole>();
    }

    [Key]
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    [EnumDataType(typeof(Operation))]
    public Operation Operations
    {
        get { return _operations; }
        set { _operations = value; }
    }
}

but it doesn't work.

Is there any elegant way that can map it?

I think creating an int-type property is not the best way.

like image 456
Scott 混合理论 Avatar asked Aug 28 '12 06:08

Scott 混合理论


1 Answers

The only way in .NET 4.0 is to use int property persisted to database and non-mapped enum property which will convert the int internally (or during entity loading and entity persistence). Alternatively you can try a wrapper approach.

.NET 4.5 supports enums directly but I don't think Flags are supported (Edit: Check Kamyar's comment).

like image 112
Ladislav Mrnka Avatar answered Oct 18 '22 20:10

Ladislav Mrnka