Saving multiple values of an enum in the database

3

I would like to be able to save several options of an enum (day of the week) something like 1.3.5 (Monday, Wednesday, Friday)

As the modeling described here.

I created a model

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

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

This 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
    }

However when giving the migrations it creates as int

In the view the Insert I'm doing

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

I'm thinking of creating the field as a string, creating a viewmodel to send the field as a string and the enum, and then in the controller do the union, I do not know if this is a gambiarra, but I think it would work.

Note: The [flag] field of the enum together with @Html.EnumDropDownListFor does not run, I need to disable the 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 without success.

    
asked by anonymous 05.10.2016 / 16:13

1 answer

2

Modify your flags so that they match bits, thus enabling 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 adding values:

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

To check if a given day is present in a given value, use a Boolean operator AND:

var temSexta = QuintaSextaESabado && DiaDaSemana.Sexta;
  

Tip: Do not use diacritics (accents, cedilla, etc.) on objects. Notice how I modified the entries in your enum for Terca and Sabado .

    
05.10.2016 / 17:05