Class attribute with pre-determined values

3

I want to create a class attribute for the gender ( M or F ), which by default the person can already select. Is it possible to create an array with these values ( M and F ) already default without typing, or should I do this in the same layout?

[DisplayName("SEXO")]
[StringLength(1, MinimumLength = 1, ErrorMessage = "Selecione o Sexo")]
public string Sexo { get; set; }

The way it is here (above) would be a field for the person to type, I thought about doing one type:

public list<Sexo>...

CHANGE

namespace Projeto.Models
{
    public enum Sexo { M = 1, F = 2 }

    public class Pessoa
    {
        [Key]
        public int PessoaID { get; set; }

        [DisplayName("Nome")]
        [Required(ErrorMessage = "Preencha o nome")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O nome deve ter de 3 a 255 caracteres")]
        public string Nome { get; set; }

        ...

        [DisplayName("SEXO")]
        [Required(ErrorMessage="Selecione o sexo")]
        [StringLength(1, MinimumLength = 1, ErrorMessage = "Selecione o Sexo")]
        public Sexo Sexo { get; set; }

    }
}

When doing Add-Migration I get the following message:

    
asked by anonymous 18.01.2017 / 23:23

1 answer

2

You can use enum with defined values, in the case M = 1 and F = 2 :

public enum Sexo
{
    Masculino = 1,
    Feminimo = 2
}
[DisplayName("SEXO")]
public Sexo Sexo { get; set; }

Note: In link has the step-by-step explanation. The field that is written to the database is an integer corresponding values of Male and Feminimo of enum Sexo .

References:

18.01.2017 / 23:44