Entity Framework 6 Code First - Required Enum data type not working

tit picture tit · Jun 22, 2014 · Viewed 28.3k times · Source

I am generating a database table using an required enum field. However, when feeding the table, it is possible to omit to feed the enum field: EF will not throw any error message but will feed the field with 0 value. Can you help me understanding what is happening? Thanks

   public enum TestEnum {
        test1=1,
        test2=2,
        test3=3,
        test4=4
    }

public class TestEnumClass
{
    [Key]
    public int id { get; set; }
    [Required(ErrorMessage = "Required"), Display(Name = "Test Enum")]
    public TestEnum test{ get; set; }
}

Answer

Petr Hruzek picture Petr Hruzek · Jul 23, 2014

Use RangeAttribute:

public enum TestEnum
{
    test1 = 1,
    test2 = 2,
    test3 = 3,
    test4 = 4
}

public class TestEnumClass
{
    [Key]
    public int id { get; set; }

    [Range(1, 4), Display(Name = "Test Enum")]
    public TestEnum test{ get; set; }
}