How to create a table corresponding to enum in EF6 Code First?

c# ef-code-first entity-framework entity-framework-6 enums

Accepted Answer

This is the suggested method because EF doesn't handle it automatically, yes.

I recommend making a few changes to the content you gave.

your enum, rename it

public enum FacultyEnum { Eng, Math, Eco }

Make a class to stand in for the table.

public class Faculty
    private Faculty(FacultyEnum @enum)
        Id = (int)@enum;
        Name = @enum.ToString();
        Description = @enum.GetEnumDescription();

    protected Faculty() { } //For EF

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    [Required, MaxLength(100)]
    public string Name { get; set; }

    public string Description { get; set; }

    public static implicit operator Faculty(FacultyEnum @enum) => new Faculty(@enum);

    public static implicit operator FacultyEnum(Faculty faculty) => (FacultyEnum)faculty.Id;

Your model makes the class reference.

public class ExampleClass
    public virtual Faculty Faculty { get; set; }

Make an extension method to obtain an enum's description and seed values.

using System;
using System.ComponentModel;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;

public static class Extensions
    public static string GetEnumDescription<TEnum>(this TEnum item)
        => item.GetType()
               .GetCustomAttributes(typeof(DescriptionAttribute), false)
               .FirstOrDefault()?.Description ?? string.Empty;

    public static void SeedEnumValues<T, TEnum>(this IDbSet<T> dbSet, Func<TEnum, T> converter)
        where T : class => Enum.GetValues(typeof(TEnum))
                               .Select(value => converter((TEnum)value))
                               .ForEach(instance => dbSet.AddOrUpdate(instance));

Configuration should include the seed. cs

protected override void Seed(Temp.MyClass context)
    context.Facultys.SeedEnumValues<Faculty, FacultyEnum>(@enum => @enum);

the DbContext's enum table should be added.

public class MyClass : DbContext
    public DbSet<ExampleClass> Examples { get; set; }
    public DbSet<Faculty> Facultys { get; set; }

Use it

var example = new ExampleClass();
example.Faculty = FacultyEnum.Eng;

if (example.Faculty == FacultyEnum.Math)

To recall

If you don't include virtual in the Faculty property, you must perform an Eager Load using the Include method from the DbSet.

var exampleFromDb = dbContext.Examples.Include(x => x.Faculty).SingleOrDefault(e => e.Id == 1);
if (example.Faculty == FacultyEnum.Math)

Use any virtual faculty attribute if it exists.

var exampleFromDb = dbContext.Examples.Find(1);
if (example.Faculty == FacultyEnum.Math)
1/1/2016 5:39:02 PM

Popular Answer


Related Questions


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