Working with Enums of type CHAR, using C # and Entity Framework

5

I would like to know how to map my entity that uses an Enum of type char through the 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 configured 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 saving a Location with North Zone, the N character is saved in the Bank

    
asked by anonymous 09.06.2017 / 15:31

1 answer

1

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);
    
27.07.2017 / 00:36