Im currently working on a .Net application that has a PostgreSQL backend. Im using NpgSQL to connect the two. When I try to do simple data retrieval, NpgSQL returns the following error:
42601: syntax error at or near "get_all_reviews"
PostgreSQL Function being called:
create or replace function public.get_all_reviews()
returns TABLE(review_text text, review_sentiment integer) as $$
begin
return query select rec.review_text, rec.review_sentiment from reviews as rec;
end;
$$ language plpgsql;
ALTER FUNCTION public.get_all_reviews()
OWNER TO postgres;
C#/NpgSQL:
public List<Review> GetReviews()
{
var reviews = new List<Review>();
var postgresqlConnection = new NpgsqlConnection("Server=localhost;Port=5432;User Id=user;Password=password;Database=db;");
postgresqlConnection.Open();
var command = new NpgsqlCommand("get_all_reviews", postgresqlConnection);
try
{
var dataReader = command.ExecuteReader();
...do stuff
postgresqlConnection.Close();
}
catch(Exception ex)
{
throw ex;
}
return reviews;
}
The exception occurs on command.ExecuteReader()
. However, if I run the following query in pgAdmin4, I get the desired results from the aforementioned function:
select get_all_reviews()
The SQL that you successfully executed was:
select get_all_reviews()
When you ran it from C# though, you ran different SQL:
get_all_reviews
As such, the solution is to use the working SQL in C# as well:
var command = new NpgsqlCommand("select get_all_reviews()", postgresqlConnection);
This is necessary, since the FUNCTION returns a TABLE, which you are SELECTing from.