How to work with CHAR Enums using C# and Entity Framework

Question:

I would like to know how to map my entity that uses an Enum of type char by Entity Framework, using FluentApi.

I have the following Enum:

public enum Zona
{
    Norte = 'N',
    Sul = 'S'
}

And my Entity:

public class Local
{
    public Guid RioId { get; set; }
    public string Nome { get; set; }
    public Zona Zona { get; set; }
}

I configure the entity as follows:

public class LocalMapping : EntityTypeConfiguration<Local>
{
    public LocalMapping()
    {
        ToTable("Local");

        HasKey(r => r.LocalId);

        Property(r => r.Nome).IsRequired();

        Property(r => r.Zona).IsRequired(); 
    }
}

How do I register my Enum Zone as varchar(1) in the database, so that when I save a Location with North Zone, the character N is saved in the Bank

Answer:

You could use an enum of your own:

public class EnumBase
{
    public EnumBase()
    {
        Locals = new HashSet<Local>();         
    }

    public int EnumBaseId { get; set; }
    public string Nome { get; set; }
    public string Codigo { get; set; }
    public int? ValorEnum { get; set; }

    public ICollection<Local> Locals { get; set; }
}

public class Local
{
    public Guid RioId { get; set; }
    public EnumBase Zona { get; set; }
    public int? ZonaId { get; set; }
    public Zona Zona { get; set; }
}

Then you Map in EnumBase:

HasMany(c => c.Locals)
                  .WithOptional(x => x.Zona)
                  .HasForeignKey(c => c.ZonaId);
Scroll to Top