简体   繁体   中英

C# POCO Classes with Postgres Database and Proper Casing (without using Entity Framework)

I have created a database using Postgres SQL and I want to interact with this database using the Npgsql ADO.Net provider library. All of my Postgres tables and columns have lowercase naming, but, I want my C# POCOS to have uppercase naming.

For instance, in Postgres my user table is named "users" (plural) and it has a user_name column. In C#, I want to map that table and column to a class called User (singular) with a property called UserName.

All of the examples I see for using data annotations to accomplish this are using an ORM like EF, but I don't want to use an ORM, just raw Npgsql. Will data annotations work if I'm just using Npgsql (raw) without an ORM? For instance:

[Table("users")]
class User
{
  [Column("user_name")]
  [Required]
  public string UserName { get; set; }
}

Npgsql doesn't do any sort of mapping for you - it's just responsible for sending your SQL commands to PostgreSQL and providing you with the results. It's up to you to write whatever SQL you want - Npgsql is totally unaware of your POCOs or any annotations you have on them.

If you don't want to hand-write SQL you need an O/RM such as Entity Framework or some other mapping layer. If you do decide to write your own SQL it's recommended you look at Dapper.

Use QueryFirst (disclaimer: which I wrote) It will generate your pocos based on the schema returned from your query. The poco class name is based on the name you give the query, so you control the casing. To control the casing of the columns in the result set, use SQL aliases. (Result columns become properties in the generated POCO). No ORM, no dependencies, full control over your sql, all queries continually integration tested. All data access continually validated. What's not to like?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM