Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw SQL in Postgres with EntityFramework Core

Say I have a customer table and would like to make a query with raw SQL. The below code does not work:

List<Customer> customers = _db.Customer.FromSql("SELECT * FROM Customer").ToList();

It fails with the error code

'42P01: relation "customer" does not exist'

like image 759
Thorkil Værge Avatar asked May 21 '26 11:05

Thorkil Værge


1 Answers

In certain situations Postgres will produce case sensitive table names. This can happen if you use helper programs to create the database, like SQL Manager. This affects how you have to reference the table. You need to add quotes around the table names like so: "Customer".

You may need to include the schema as well. This should work:

List<Customer> customers = _db.Customer.FromSql("SELECT * FROM \"public\".\"Customer\"").ToList();

Assuming your schema name is "public". Otherwise insert your schema name instead.

like image 178
Thorkil Værge Avatar answered May 23 '26 00:05

Thorkil Værge