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

Asked

Viewed 100 times

0

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

- tb_usuario

  • usu_id
  • last name
  • usu_data_nasc

- tb_product

  • pro_id
  • pro_name
  • pro_desc_resumida
  • pro_desc_completa

When using 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 do know that in the code it’s not good practice, and I don’t even want to be named after properties like: pro_desc_completa. But how: descriptionComplete.

However, how do I do this? It is 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?

1 answer

1


In the context of your application, the class where you configure the 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 its entities:

Supposing:

tb_usuario

  • usu_id
  • last 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 how:

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 use data:

[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; }
}
  • I understood, but I’ll have to do the mapping like this in the modelBuilder for all my classes, and all my properties. It’s going to be very hard work. I know that in java, we were able to map through an Annotation, I thought in c# it would have something like...

  • another issue, is, my context, is automatically generated by ADO.net, and comes with the warning that the code can be changed if my model is updated. So it’s not safe to touch it. So I can create a class, inherit from my context to do this implementation of Onmodelcreating?

  • 1

    You can use Annotation as well: [Table("tb_usuario")] decorating its class and , [Column("usu_id")] its properties. I will add the answer.

Browser other questions tagged

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