c# – How to simplify type declaration with Entity Frameowrk?

Question:

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 define .HasColumnType("datetime"); , my doubt is;

Is there a more practical way to somehow define this 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 bunch of 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);
}

Answer:

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

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

Here's the code:

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

Note: It can also be done for other types.

Another configuration example

Create a class and inherit with Convention and in your Construtor write the same code for configuring the DateTime column.

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

In OnModelCreating work with convention as follows:

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

Some additional examples:

Setting column size:

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

Setting column size for a given column name:

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

Referencias:

Scroll to Top