How to change and maintain mapping of classes and properties using ADO.net

0

When using a database I have tables and columns with names like:

- tb_user

  • usu_id
  • usu_name
  • usu_data_nasc

- tb_product

  • pro_id
  • pro_name
  • pro_desc_resumida
  • pro_desc_completa

When you use ADO.NET Entity Data Model - > EF Designer From Database , it creates the entities classes in my project with the same name as the tables, and the properties with the same name as the database columns. But I know that the code is not good practice, and I do not want to have the name of properties like: pro_desc_completa . And yes like: descriptionComplete .

But how do I do this? Is it possible to map a property or class, with a table and have different names, using EF Designer From Database?

Or what would be the best approach to use?

    
asked by anonymous 07.06.2017 / 13:40

1 answer

1

In the context of your application, the class where you configure EF and define the DBSet, can also customize other information. You can override the method: onModelCreating using fluent API and manually define the mapping of your entities:

Assuming that:

tb_user

  • usu_id
  • usu_name
  • usu_data_nasc

Turned into:

public class Usuario{
    public int id {get; set; }
    public string nome {get; set; }
    public DateTime dataNascimento {get; set; }
}

You would map as:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Usuario>()
        .ToTable("tb_usuario")
        .Property(p => p.id)
        .HasColumnName("usu_id");
}

Or, you can still use data annotation:

[Table("tb_usuario")]
public class Usuario{
    [Column("usu_id")]
    public int id {get; set; }

    [Column("usu_nome")]
    public string nome {get; set; }

    [Column("usu_data_nasc")]
    public DateTime dataNascimento {get; set; }
}
    
07.06.2017 / 14:14