Map a CHAR-like field in the database to a bool-like field in C#, with Fluentnhibernate?

Asked

Viewed 295 times

3

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

Today, in my application I am circumventing this problem with a "gambiarra", where I mapped my attribute Ativo, as string and created another attribute bool IsAtivo who does something similar to this:

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

Nor need I comment that it is horrible that I already know, so I want to improve, when I implemented it I did not have time to look for better.

So I was wondering if you know any way to map this to the , by mapping the ?

// Acredito que alguma configuração aqui pode resolver meu problema
Map(t => t.Ativo, "ATIVO")

1 answer

3


In Nhibernate there is an abstract and specific Usertype for this case, called CharBooleanType, that allows you to mask a type char as bool. Create a class that inherits this type and override properties TrueString and FlaseString:

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 out as a custom type pointing to this type.

Fluentnhibernate:

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

HBM.XML

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

At this link talks a little about the creation of UserTypes.

  • 2

    +1 Interesting. Implementation of NHibernate.Type.CharBooleanType.

  • Thank you for the reference Miguel. :)

  • @Felipeoriani, thank you very much, for the help, very interesting that way. It worked perfectly here.

  • Would it also be possible to use Enumchartype<T> in the same way? In the legacy database I have a field that is char(1) "F" or "J". Individual or Legal, and I would like to map to a boleano.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.