Conversion of Types with Fluenti API to EF Core 2.1

Asked

Viewed 43 times

0

I would like to know if it is possible to make the following conversion:

public class Pessoa 
{
    public bool Ativo { get; set; }
}

public class PessoaMap: IEntityTypeConfiguration<Pessoa>
{
    public virtual void Configure(EntityTypeBuilder<TEntity> builder)
    {
         builder.Property(x => x.Ativo)
            .HasConversion(?) 
         // Converter o meu campo bool em char no banco de dados, por exemplo, quando for true inserir no banco de dados "S", ou inverso "N"
    }
}

    Tabela Pessoa

    | Ativo |
|1| |  'S'  |
|2| |  'N'  |

1 answer

0


You need to create the conversion via lambda, the first, is the parse of the bool for char, the second, of char for bool (used when loading from the database)

public class PessoaMap: IEntityTypeConfiguration<Pessoa>
{
    public virtual void Configure(EntityTypeBuilder<TEntity> builder)
    {
         builder.Property(x => x.Ativo)
            .HasConversion(
                x => x.Ativo ? "S" : "N",
                x => x.Equals("S"));
    }
}

There are several pre-defined converters that can be used, including some for your case, the above example is a demonstration of a handmade converter, and can serve as an example for other conversions.

Existing converters can be found in the response reference link.

Source: Value Conversions - Microsoft

  • Thanks, that’s what I needed, there was only one though, I can’t do it using the Valueconverter<bool, char> () class and put the expression in here, for some reason it only accepts string field instead of char, then in that case I had to do the conversion inside the same Hasconversion.

  • Cool guy! I didn’t really test the solution because I wrote by cell phone, but I’ve updated.

Browser other questions tagged

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