When the property is not int how to force Entity to create a field in the table as nullable:false

Asked

Viewed 54 times

0

Migration is generating the name field in the table as nullable:true i don’t want it to be true, as I do to solve this problem?

 public class Professor
{
    public string Id { get; set; }
    public string Nome { get; set; }
    public string Sobrenome { get; set; }
    public IList<ProfessorTurma> Turmas { get; set; }

    public Professor(string nome, string sobrenome)
    {
        Nome = nome;
        Sobrenome = sobrenome;
        //Turmas = new List<Turma>();
    }

    public bool ValidaProfessor()
    { 
        if(string.IsNullOrEmpty(Nome) || string.IsNullOrEmpty(Sobrenome)
            || Nome.Any(x => char.IsDigit(x)) || Sobrenome.Any(x => char.IsDigit(x))
            )
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

public partial class TurmaUsuarioProfessorProfessorTurma : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Professores",
            columns: table => new
            {
                Id = table.Column<string>(nullable: false),
                Nome = table.Column<string>(nullable: true),
                Sobrenome = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Professores", x => x.Id);
            });

1 answer

1


As in C# string are always of the type by reference and with this they always accept null values because they are nullable, EF create fields as if they accept null data by default.

To place a requirement on the property you can use Data Annotation [Required] on top of your property, ex:

public class Professor
{
    public string Id { get; set; }
    [Required]
    public string Nome { get; set; }
    [Required]
    public string Sobrenome { get; set; }
    public IList<ProfessorTurma> Turmas { get; set; }
}
  • Understood perfectly and put into use, thanks for the help!

  • @Robsonjunior if the answer answered you, you can accept it

Browser other questions tagged

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