How to create a table corresponding to enum in EF6

2020-01-26 21:09发布

I've followed MSDN on how to handle enumerations in Code First for EF6. It worked, as supposed to but the field in the created table that refers to the enumerator is a simple int.

I'd prefer a second table to be produced, the values of which would follow the definition of the enumerator in C# code. So, instead of only getting a table corresponding to Department in the example on MSDN, I'd also like to see a second table populated by the items from Faculty.

public enum Faculty { Eng, Math, Eco }     

public partial class Department 
{ 
  [Key] public Guid ID { get; set; } 
  [Required] public Faculty Name { get; set; } 
}

Researching the issue, I stumbled upon a solution, which suggests creating a table for the enumeration and populating it explicitly by seeding.

It appear to me as a cumbersome approach and a lot of work that should be handled automagically. After all, the system knows what actual values that constitute the enumeration. From DB point of view it's still data rows, just as the entities that I create but from OO aspect, it's not really a data - rather a type (loosely expressed) that can assume a finite and onbeforehand known number of states.

Is the approach of populating the table "manually" recommended?

7条回答
趁早两清
2楼-- · 2020-01-26 21:56

You should add : byte in front of enum declaration :

enum MyFieldEnum : byte{
    one = 1,
    two = 2,
    three = 4
}

In database, you should see TINYINT and no need to casting !

查看更多
登录 后发表回答