Using enumeration values ​​in a domain model with EF Code First approach

I use the Entity Framework Code First approach in my MVC application, and I have some entity classes for each table in the database. On the other hand, I need to use some search values, i.e. gender, status, for which I do not want to create a separate model or domain table, and for this reason I need to determine the enum values ​​in the corresponding domain model class or a separate class. Although there are many examples on the Internet, I have not found a suitable one for EF and MVC . Could you give an example of a use that fulfills these requirements?

Note. I use MVC5 and EF6 . Here is my Visitor entity class and a sample object that can be defined in a separate class (.cs file) or in the same class (.cs file):

 namespace MyProject.Entities { public class Visitor { [Key] public int VisitorID { get; set; } public string VisitorName { get; set; } //[ForeignKey("ReasonOfVisit")] public byte ReasonOfVisit { get; set; } //code omitted for brevity } public enum ReasonOfVisit { NotSet = 0, Business meeting = 1, Periodic visit = 2, Getting information = 3, Leaving package = 4 } } 
+5
source share
2 answers

If you want to use enumerations with your EF models, you can try the following solution:

  public class User { public string Id { get; set; } public RegistrationStatus RegistrationStatus { get; set; } } public class UserConfiguration : EntityTypeConfiguration<User> { public UserConfiguration() { this.Property(x => x.RegistrationStatus) .HasColumnType("int") .IsRequired(); } } public enum RegistrationStatus { Pending = 1, Active = 2, Blocked = 3 } 

Of course, it is simplified as much as I can. What you basically do is map your enumeration to some kind of primitive type. EF automatically converts the values, and you can use them the way you would like.

+3
source

With entity framework 5.0 onwards, you can simply use the enumeration:

 namespace MyProject.Entities { public enum ReasonOfVisit { NotSet = 0, For business reason = 1, For control = 2, For lefting package = 3, For leisure = 4 } public class Visitor { ... public ReasonOfVisit ReasonOfVisit { get; set; } ... } } 

If you use EF <5.0, you can use a property of type enum mapped to the byte / int property

 public class Visitor { ... public byte ReasonOfVisitAsByte { get; set; } public ReasonOfVisit ReasonOfVisit { get { return (ReasonOfVisit)ReasonOfVisitAsByte; } set { ReasonOfVisitAsByte = (byte)value; } } ... } 

PS As for your questions:

What will be the data type of the enumeration values

EF is likely to use int type

How to define string values ​​in this enumeration

You cannot use strings directly, but if you use attributes and make extra efforts, you can set the enumeration to return a string directly, not its int value. You can read about it here.

+2
source

Source: https://habr.com/ru/post/1238236/


All Articles