Map a field of type CHAR in the database to a field of type bool in C #, with FluentNHibernate?


In the database I have a ATIVO field of type CHAR(1) , where 'T' = true and 'F' = false .

Now, in my application I'm getting around this problem with a "gambiarra", where I mapped my Ativo attribute to string and created another bool IsAtivo attribute that does something similar to this:

public bool IsAtivo
    get { return Ativo == "T"; }
    set { Ativo = value ? "T" : "F"; }

No need to comment that it's horrible that I already know, so I want to improve, when I implemented this I did not have time to look for ways to improve.

So I'd like to know if you know of any way to map this to , by mapping the ?

// Acredito que alguma configuração aqui pode resolver meu problema
Map(t => t.Ativo, "ATIVO")
asked by anonymous 02.04.2014 / 19:55

1 answer


In NHibernate there is an abstract and specific UserType for this case, called CharBooleanType , which allows you to map a type char to bool . Create a class that inherits this type and override the TrueString and FlaseString properties:

public class ActiveBoolType : CharBooleanType 
   public ActiveBoolType()
         : base(new AnsiStringFixedLengthSqlType(1)) { }

   protected override string TrueString 
       get { return "T"; }

   protected override string FalseString 
       get { return "F"; }

   public override string Name 
       get { return "inverted_bool"; }

Then just map it as a custom type pointing to this type.


Map(x => x.IsAtivo).Column("ATIVO").CustomType<ActiveBoolType>();


<property name="IsAtivo" 
          type="MyAssembly.MyNamespace.ActiveBoolType, MyAssembly" />

In this link talk a little about creation of UserTypes .

02.04.2014 / 20:16