0

How can I use enum in Visual C# ASP .NET MVC 4 Web Application?

I have a mySQL database with a table "flight" that contains a feild "flightDay" that uses the type enum('Monday', 'Tuesday', 'Wednesday', 'Thursday', utf8_bin

how can I make the class of the table Flight compile/work? in the model file of my application.

[Table("flight")]
public class Flight
{
    [Key,  Column(Order = 1)]
    public int id { get; set; }
    public int route { get; set; }
    public enum  flightDay { get; set; } **// How to make this work?**
    public int aircraft { get; set; }

}
2
  • When you retrieve it from database you have to cast it from string to enum type Commented Sep 24, 2014 at 22:21
  • @Dan Hunex Please can you explain how to do that? Commented Sep 24, 2014 at 22:22

2 Answers 2

1

Store them as integer id's. Optionally as a foreign key to a Days table as a code table to support lookups from SQL.

public enum Day { Monday = 1, Tuesday =2, ... }

[Table("flight")]
public class Flight
{
    [Key,  Column(Order = 1)]
    public int id { get; set; }
    public int route { get; set; }
    public int flightDayId { get; set; } 

    // Provides enum abstraction for flightDayId
    public Day FlightDay { 
      get { return (Day)flightDayId; } 
      set { flightDayId = (int)value; }
    }
    public int aircraft { get; set; }

}
Sign up to request clarification or add additional context in comments.

Comments

0

There is no enum corresponding data type in sql . So you have to bring it as string in the c# code and cast it ( Enum.TryParse ) to the corresponding enum. So you cannot make the database entity to have enum property, change it to stirng

    string FlightDay{get;set;}

Here is an example

public class Flight
{
    [Key,  Column(Order = 1)]
    public int id { get; set; }
    public int route { get; set; }
    public String  flightDay { get; set; } 
    public int aircraft { get; set; }

    [NotMapped]
    public FlightDays FlightDayEnum
    {
        get
        {
            FlightDays day;
            Enum.TryParse<FlightDays>(flightDay, out day);
            return day;
        }
    }

   }

    public enum FlightDays
    {
        Monday,
        Tuesday,
        Wendsday,
        Thursday,
        Friday,
        Saturday,
        Sunday
     }

In the DB, you should have the flight days spelled exactly the same as the enums.

In the example above, the 'FlightDayEnum' is not mapped to the database but instead it serves you as a converter between the string and the enum.

1 Comment

Would this be in the set method? get method? could you give me an example of one day?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.