Naming C # classes from bad table columns

I have used Entity Framework and SQL Server database so far. Therefore, I can represent my table name as a class name and property names as properties like the following.

class Product{ public string Id { get; set;} public string Name { get; set;} } 

The names of the tables and columns are the same as my class.

But now I will work on a project that uses the Postgresql database. Table names and column names are as follows.

  • Tables products , product_categories (lowercase)
  • Columns product_id, product_name, category_id , ....

Therefore, I do not want to use class names like this:

 class products { public string product_id { get; set; } public string product_name { get; set; } public string category_id { get; set; } } 

It looks like ugly naming conventions. How can I solve this problem?

+5
source share
2 answers

Use table and column attributes. From MSDN Example :

 [Table("InternalBlogs")] public class Blog { [Column("BlogDescription", TypeName="ntext")] public String Description {get;set;} } 
+6
source

A general approach is to map objects to your domain classes, which you name using standard C # conventions.

So, in this table product_id, product_name, categori_id, .. you point to:

 public class Product { public int Id { get; set; } public string Name { get; set; } public int Category { get; set; } } 

Then you create the mapper helper, which translates the object into a domain object:

 public Product ProductMapper(EntityProduct entity) { return new Product { Id = entity.product_id, Name = entity.product_name, Category = entity.category_id, } } 

I leave the decision for you whether mapper should be a separate helper class, a static method in the Product class. In addition, when saving data, you change the process, that is, you map the domain object to the entity.

0
source

Source: https://habr.com/ru/post/1209268/


All Articles