Use the value of a constant to set a property in the mapping with EF Core

Asked

Viewed 36 times

1

I am mapping a class (System) in EF Core, but I would like to create constants for the size of the characters, because when I go to map the class, I would just change the value of the constant and it would change everywhere in the system. Only I don’t know how to use the constant in my Dbcontext.cs. Someone could help me?

 public class Sistema
    {
        public const int TamanhoMaxDescricao = 45;

        public int SistemaId { get; set; }
        public string Descricao { get; set; }
        public string Versao { get; set; }

        public virtual ICollection<BackupAgendamento> BackupsAgendamentos { get; set; }
        public virtual ICollection<Tabela> Tabela { get; set; }
        public virtual ICollection<SistemaBackup> SistemaBackups { get; set; }
    }


modelBuilder.Entity<Sistema>()
                .Property(s => s.Descricao)
                .HasColumnName("Descricao")
                .HasColumnType("Varchar(50)") //Usar constante aqui para informar o tanho
                .HasMaxLength(50)
                .IsRequired();
  • I’ve never used it, but you’re having some trouble?

  • I cannot call the count... It does not appear... Ex: . Hasmaxlength(System.Tam

  • It doesn’t show up where? It’s not to trim anything.

1 answer

2


If the variable is already as public const just access it:

Sistema.TamanhoMaxDescricao;

Would look like this:

modelBuilder.Entity<Sistema>()
                .Property(s => s.Descricao)
                .HasColumnName("Descricao")
                .HasColumnType("varchar") 
                .HasMaxLength(Sistema.TamanhoMaxDescricao)
                .IsRequired();

observe the HasColumnType that stands only "varchar", the field size is reported in HasMaxLength

  • Thank you for having responded Rovann... When I try to call the counting, it does not appear... Ex: . Hasmaxlength(System.Tam...

  • puts your code the way it is in your project, if it is two snippets of code, separate them also in the view of the question. Just to understand what scope the modelBuilder

  • I managed to solve the problem rsrsrssrs VS was crazy.... Kind of confusing with Dbset.... I had to specify the path: Systemscommercial.domain.Entities.Sistema.Tamanhomaxdescription.

Browser other questions tagged

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