Using enum values in Domain Model with EF Code First approach
Asked Answered
G

2

8

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
    }
}
Gouache answered 15/12, 2015 at 8:40 Comment(4)
@Fabjan Sorry, you are right :) I added my effort, could you help pls? Thanks...Gouache
If i am not mistaken starting from EF 5.0 enums are supported out of the box effectively meaning that you can just use your enum in model - public ReasonOfVisit ReasonOfVisit { get; set; }Indifference
What exactly is not working? You get errors? This should work out of the box, as long as the num field in your database is defined as an int or smallint.Bogusz
@L-Three The only problem is the enum values changes to its id after returning from controller to view (I try to return in JSon format). In addition to this, I want to use string values composed of multiple words as enum values. Any idea?Gouache
K
3

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.

Kinser answered 15/12, 2015 at 8:49 Comment(7)
This mapping is not needed, EF does this automatically.Bogusz
@L-Three Haven't known about it :)Kinser
@Kamo Thanks for reply. Actually I use EF6 and I think there is no need to use the UserConfiguration part. Anyway, I am wondering how to use string values in enums in this example i.e. "Business meeting"?Gouache
@Christof I believe you should ReasonOfVisit as an enum and just parse it when needed.Kinser
Voted+. But the only problem is display the multiple word values of enum. Any idea?Gouache
@Christof Could you elaborate on that?Kinser
@Kamo Here are the detailed explanations regardin to the problem. Could you please have a look at? Thanks.Gouache
I
3

With entity framework 5.0 onwards you can just use your enum :

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're using EF < 5.0 you can use enum type property mapped to byte/int property

public class Visitor
{
    ...

    public byte ReasonOfVisitAsByte { get; set; }

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

    ...
}

P.S. Regarding your questions :

What will the data type of the enum values

EF will most likely use int type

How can I define string values in this enum

You cannot use strings directly but if you use attributes and make some additional efforts it is possible to set that enum returns string directly and not its int value. You can read more about it here

Indifference answered 15/12, 2015 at 9:33 Comment(2)
Thanks for reply. It seems to be working, but enum values convert to its id values after passing from the controller to the view. Now I have 2 questions: 1) What will the data type of the enum values? Because we have not set here, will it be assigned automatically? 2) How can I define string values in this enum i.e. "Business meeting"?Gouache
Many thanks for your reply. I tried some methods to display the multiple word values of enum i.e. Dealing with Enum in MVC 5.1 but still cannot display them. Display property is ok, but I am not sure what I missed. Any idea? On the other hand as this answer is very helpful for me I voted+Gouache

© 2022 - 2024 — McMap. All rights reserved.