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

c# entity-framework-6 enumeration

Question

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; }
}
1
24
6/22/2014 10:34:57 AM

Accepted Answer

This is because of how Enum types are handled in .NET. If you do not provide a value, it is effectively the same as if value 0 was assigned. If your enum has the value of 0 defined then the correct value is assigned to enum variable. If the value is not assigned - it still assigns value of 0 but it fails when you try to use it because it cannot convert the int to the correct enum value.

In your case I suggest if it is possible to add a value of 0 and assign it to a specific value or assign value of Default, Null or something similar to your enum, e.g.

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

If you want to validate it then you can compare that value is not equals to 0.

18
6/22/2014 10:42:29 AM

Popular Answer

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; }
}


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