How to simplify the type declaration with Entity Frameowrk?

3

I have some tables with several fields of type datetime, and for all of them I need to create a validation in OnModelCreating () for this type, that is, I need to set .HasColumnType("datetime"); , my doubts are;

Is there a more practical way to define this in some way as a default?

Something like;

 modelBuilder.Entity<Usuarios>()
       .Property(so => so.Contains("dt)) // contem dt inicia dos campos datetime
       .HasColumnType("datetime");

The idea and not having to repeat this many times as I had to do below.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Usuarios>()
       .Property(so => so.dtAdmissao)
       .HasColumnName("dtAdmissao")
       .HasColumnType("datetime");
    modelBuilder.Entity<Usuarios>()
      .Property(so => so.dtInclusao)
      .HasColumnName("dtInclusao")
      .HasColumnType("datetime");
    modelBuilder.Entity<Usuarios>()
      .Property(so => so.dtNascimento)
      .HasColumnName("dtNascimento")
      .HasColumnType("datetime");

    base.OnModelCreating(modelBuilder);
}
    
asked by anonymous 24.11.2016 / 13:59

1 answer

2

The way to leave a global setting for Entity Framework is in method OnModelCreating with line

  

modelBuilder.Properties<DateTime>().Configure(x => x.HasColumnType("datetime"));

Follow the code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Properties<DateTime>().Configure(x => x.HasColumnType("datetime"));
}

Note: can also be done for other types.

Another configuration example

Create a class and inherit with Convention " and in its Construtor it writes the same configuration code from the DateTime .

public class DateTimeConvention : Convention
{
    public DateTimeConvention()
    {
        this.Properties<DateTime>()
            .Configure(c => c.HasColumnType("datetime"));        
    }
}

No OnModelCreating work with convention as follows:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Conventions.Add(new DateTimeConvention());
}

Some additional examples:

Configuring column size:

modelBuilder.Properties<string>()
                .Configure(c => c.HasMaxLength(500));

Configuring the column size for a given column name:

modelBuilder.Properties<string>()
                .Where(x => x.Name == "Name")
                .Configure(c => c.HasMaxLength(250));

References:

24.11.2016 / 14:26