Storing multiple values of an Enum in the database

Asked

Viewed 438 times

3

I wish I could save several options of an Enum (day of the week) something like 1,3,5 (Monday, Wednesday, Friday)

As modeling described here.

I created a model

public class Horario
{
[Key]
public int ModalidadeProfessorSalaHorarioId { get; set; }

    [DataType(DataType.Text)]
    public DiaDaSemana DiaDaSemana { get; set; }
}

That day of the week is an Enum

 [Flags]
    public enum DiaDaSemana
    {
        Domingo=0,
        Segunda=1,
        Terça=2,
        Quarta=3,
        Quinta=4,
        Sexta=5,
        Sábado=6
    }

But when giving Migrations it creates as int

In the view I’m doing Insert

@Html.EnumDropDownListFor(model => model.DiaDaSemana, new { @class = "form-control", multiple = "true"  })

I’m thinking about creating the field as a string, creating a viewmodel sending the field as string and Enum, and then in the controller doing the union, I don’t know if this is a scam, but I think it would work.

OBS: The field [flag] of Enum together with the @Html.EnumDropDownListFor do not turn, need to disable flag

O tipo de retorno 'Enums.DiaDaSemana' não tem suporte. O tipo não deve ter um atributo 'Flags'.
Nome do parâmetro: expression

I tried to use this solution more unsuccessfully.

  • What is the need to keep in the bank?

  • I need to save the days of the week in the bank!

  • That I understood, I’m asking the reason.

  • I put the modeling link

  • An Enum is just a Nickname for a mapping constant or id. Internally it is converted to the appropriate type. Treat as such, take int from the bank and cast. Be careful with this: https://msdn.microsoft.com/pt-br/library/sbbt4032.aspx

1 answer

2


Modify your flags to match bits, thus allowing boolean operations:

[Flags]
public enum DiaDaSemana
{
    Domingo = 1, // 0x00000001
    Segunda = 2, // 0x00000010
    Terca = 4,   // 0x00000100
    Quarta = 8,  // 0x00001000
    Quinta = 16, // 0x00010000
    Sexta = 32,  // 0x00100000
    Sabado = 64  // 0x01000000
}

So date combinations can be expressed by summing the values:

var QuintaSextaESabado = DiaDaSemana.Quinta + DiaDaSemana.Sexta + DiaDaSemana.Sabado;
//  QuintaSextaESabado = 112 decimal, 0x01110000 binario

To check whether a given day is present at a given value, use a Boolean AND operator:

var temSexta = QuintaSextaESabado && DiaDaSemana.Sexta;

Tip: Do not use diacritics (accents, cedilla, etc.) on objects. Note how I modified the entries on your Enum to Terca and Sabado.

  • and then if I have 112 decimal I can figure out which days of the week they were? how will he do that?

  • @Dorathoto using the last example of the answer; perform an AND operation between the items of enum and the stored value.

Browser other questions tagged

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