Using enum values in Domain Model with EF Code First approach

asp.net-mvc c# domain-model entity-framework enums

Question

I use Entity Framework Code First approach in my MVC application and I have some entity classes for every table in the database. On the other hand, I need to use some lookup values i.e. gender, status for which I do not want to create a separate domain model or table and for this reason I need to define enum values in a related domain model class or a separate class. Although there are many samples on the web, I have not found a suitable one for EF and MVC. Could you please give a sample usage that performs this requirements?

Note : I use MVC5 and EF6. Here is my entity class called Visitor and sample entity 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
    }
}
1
7
12/15/2015 9:36:54 AM

Popular Answer

If you want to use enums with your EF models, you can try 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 to map your enum to some primitive type. EF will convert values automatically and you can use it as you would like to.

3
12/15/2015 8:49:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow