Entity Framework: tinyint to boolean mapping

c# entity-framework mapping


by default Entity Framework maps tinyint to byte.

i tried changing the underlying type after it was generated to Boolean, but getting compilation error

Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=False,DefaultValue=]' of member blah...

is this possible in 4.0?

it wasn't my idea to use tinyint column as boolean. this was done automatically by another team using hibernate which apparently does it that way for mysql compatibility. obviously tinyint has more values than 2. I am looking for a way to map it so that anyting accept for 1 is false, or anything accept for 0 is true. either would work for me

is there a way to plug in a type translator of sorts into EF?

10/25/2010 6:36:11 PM

Accepted Answer

From MSDN's page on integer types, we see that the tinyint type represents an integer ranging from 0 to 255.

A bool, in contrast, represents only a binary 0 or 1.

Changing the default mapping from byte to bool (if it were even possible, which according to this page it seems like it's not) does not make sense -- how, for example, would you represent the value 42 (a valid tinyint) as a bool?

If you need an entity with a property of type bool, I'd suggest mapping it to a column of type bit.

10/25/2010 5:21:52 PM

Popular Answer

Actually the main reason why often integers are used in database has to due with the fact that a lot of database engines don't allow indexes on bit fields. Most database engines try to group multiple bit fields in one 'internal' byte to safe space. As a result the bit field isn't really available for indexing..

The defacto standard is that 0 equals to false and all other values equal to true. However EF does not have support for this kind of mapping. The best method is using a private shadow field declared as byte which is mapped to EF. Second you create a alias boolean property which is used by your code.

Mapping private properties with EF requires some reflection code.

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