26. January 2015 13:54
Entity Framework supports Enum properties on your model, but there’s one little gotcha that’s bitten me on more than one occasion now. In your database, you may be tempted to save space by configuring the backing column to use an integer value that takes up less space than a normal int, such as a TINYINT (byte) or SMALLINT (short). If you do though, you may get an error like the following:
System.InvalidOperationException : The 'State' property on 'Issue' could not be set to a 'System.Byte' value. You must set this property to a non-null value of type 'IssueState'.
It sounds like EF is trying to assign the raw Byte value to the property rather than converting it to an Enum member, and indeed that’s what it’s doing. Fortunately, the fix is easy: just change the base type of your enum! By default, enums derive from System.Int32, but you can change that:
public enum IssueState : byte
New = 0,
InProgress = 1,
ReadyForQA = 2,
Deferred = 10,
Closed = 20
Now EF will hydrate your entity with no complaints. Just remember to set the base type to match the column type you used in your table!
About Matt Honeycutt...
Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications.
He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.
He's also an author for Pluralsight,
where he publishes courses on everything from web applications to testing!