Saulo Vallory
Saulo Vallory

Reputation: 979

Mapping tinyint to boolean in Entity Framework

I'm sure you saw this question before. But, at least in my search, every time it is asked an answer like this: https://stackoverflow.com/a/4017148/219838 pops out. The answer is perfectly right, but doesn't cover one scenario. What if your DBA chose to use tinyint columns (according to him bit columns aren't indexable) to represent booleans and nothing in the world will make him change that?

I understand the difference between the boolean and byte values. But I DON'T CARE! What I need to know is: Is there ANY workaround to map a tinyint column to a boolean instead of a byte?

I found an ugly one describe here: http://www.saulovallory.com/how-to-map-byte-columns-to-bool-in-entityframework but it doesn't work for fluent mapping. And now I need one which does.

Upvotes: 2

Views: 2203

Answers (1)

Eranga
Eranga

Reputation: 32437

EF does not have built it custom type converters like IUserType in nHibernate. Possible workaround would be to map the column to a matching property with byte type and have another bool property with conversion logic. Because this is not a mapped property you will not be able to use it in LINQ queries.

public class MyClass
{
    public byte DatabaseColumnName { get; set; }

    [NotMapped]
    public bool DomainPropertyName 
    { 
       get
       {
            //conversion logic using DatabaseColumnName 
       }
       set
       {
           //conversion logic using DatabaseColumnName 
       }
}

Upvotes: 1

Related Questions