Tinyint(byte),SmallInt(Int16) not compatible with Enum in EF5

久未见 提交于 2019-12-20 11:13:31

问题


Using Database first design and having tinyint (or smallint) column:

[MyEnumColumn] [tinyint] NOT NULL

I mapped this column to Enum Type in EDM with

External Type: NSpace.MyEnumType
Name:MyEnumType
UnderlyingType:Byte

Where NSpace.MyEnumType is defined like this:

public enum MyEnumType 
{ One, Two, Three, All }

Only to get this error when trying to load entity from context:

Schema specified is not valid. Errors:

No corresponding object layer type could be found for the conceptual type 'EntityDataModel.MyEnumType'.

The following information may be useful in resolving the previous error:

The underlying type of CLR enumeration type does not match the underlying type of EDM enumeration type.

Same applies if I use [Smallint] and [Int16] but once I change database to [Int] and enum type to [Int32] the error is gone.

Why do I need to store enum value in 4Byte (Int) data field instead of 1Byte (Tinyint) when enums in 99.9% time don't have more than 256 items or am I missing something else?


回答1:


Well if anyone is interested the problem is in enum's default type:

public enum MyEnumType 
{ One, Two, Three, All }

Since enum defaults to type int, [Underlying Type:{Byte}] doesn't match type of [External Type] {MyEnumType:Int} so to fix it for my original tinyint field you need to define your enum like this:

public enum MyEnumType : byte
{ One, Two, Three, All }



回答2:


You need to specify both in the Model and in the Enumerator that you are using tinyInt and Byte .

in Enumerator definition public enum MyEnumType : byte { One, Two, Three, All }

then in the Model class file

 [Column(TypeName = "tinyint")]
    public MyEnumType? MyEnum { get; set; }   


来源:https://stackoverflow.com/questions/13318782/tinyintbyte-smallintint16-not-compatible-with-enum-in-ef5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!