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

Asked

Viewed 437 times

5

I would like to know how to map my entity using an Enum of the type char by 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; }
}

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 saving a Location with North Zone, the character N is saved in the Bank

1 answer

2

You could use a proper Enum:

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 the Enumbase:

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

Browser other questions tagged

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