Search code examples
c#entity-framework-4

What is easiest way to deal with converting 0/1 to False/True in EF 4.x?


The stored Proc returns a column with the value to be either 0 or 1 without converting to BIT. In my POCO, if I declare the field as

public bool MyColumn {get; set;}

I am getting this error:

The specified cast from a materialized 'System.Int32' type to the 'System.Boolean' type is not valid.

This actually makes sense since EF recognizes the returned value as an integer.

I am wondering that is there any easy way to (add annotation or use fluent api maybe) automatically convert 0/1 to False/True in the mapping behind the scene without touching the Proc?

Thanks in advance!


Solution

  • What you can do is to have another Property to represent the Boolean representation . Decorate it with NotMapped attribute so that EF won't consider it for Mapping. Do and If condition and return true /false based on the value of Other property.

    public Class Customer
    {
    
      [NotMapped]
      public bool MyColumnBool 
      {
          get
          {
             return (MyColumn ==1);
          }
      }
    
      public int MyColumn {get; set;}
      // other properties
    
    }