2

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.

4
  • @LukeMcGregor There is a link to that question in my question. I'm specifically asking for a solution different than the one provided there. (Actually the answer there doesn't provide a solution to problem at all, it's just an explanation on subject) Commented Aug 13, 2012 at 12:02
  • I was able to map tinyint(1) to boolean, by directly updating the storage model and changing the type to bool. For ex: <Property Name="active" Type="bool" Nullable="false" />. Commented Aug 13, 2012 at 12:32
  • @svallory do you got any solution to this? I'm switching from Telerik Open Access to EF Core and OpenAccess was using tinyint for bool values. Would be great to hear if you found a good solution. Commented Nov 14, 2017 at 8:25
  • Sorry @marvstar it's been a looong time since I worked on this. I don't remember if ever got around it :/ Commented Dec 5, 2017 at 17:37

1 Answer 1

1

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 
       }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly the same solution I posted on my blog, but using annotations. I don't like having two "identical" properties on my model. I was hoping to be able to do something like intercepting the save, the generated SQL or providing sort of "ValueTranslator".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.