Reading multiple values from a Postgres database using npgsql and EF Core in an ASP.NET Core MVC view:
var tulem = await ctx.Database
.SqlQuery<(string Klient, int Krediit, int Vaba)>($"select 'test',1,2")
.SingleAsync();
Throws an exception
Npgsql.PostgresException: column s.Value does not exist
How to get those values from the database?
Using ASP.NET Core 9 MVC, npgsql and EF Core
Reading multiple values from a Postgres database using npgsql and EF Core in an ASP.NET Core MVC view:
var tulem = await ctx.Database
.SqlQuery<(string Klient, int Krediit, int Vaba)>($"select 'test',1,2")
.SingleAsync();
Throws an exception
Npgsql.PostgresException: column s.Value does not exist
How to get those values from the database?
Using ASP.NET Core 9 MVC, npgsql and EF Core
Share Improve this question edited Mar 26 at 10:54 Michał Turczyn 37.8k17 gold badges54 silver badges82 bronze badges asked Mar 25 at 17:32 AndrusAndrus 28k67 gold badges214 silver badges396 bronze badges 3 |1 Answer
Reset to default 1I have tested your case and I got also the same error about Value
column not existing.
This is because you have used the type parameter wrong and there is actually one more issue:
- You should provide class that matches your select statement, i.e. properties can be mapped to the columns.
- You have two integer values - other than order of properties/columns - how would you expect to reason about it/how to map it? From purely programmatical way - they are just two numbers and it's ambigous which one is which.
So i have troubleshoot the issue as follows:
- Run the query as you did -> got the same error - I guess it is due to internal implementation of a
Tuple
and EF - EF might recognize someValue
property onTuple
and try to find such column. - Create class
and used itpublic class TestResult { public string Client { get; set; } public int Credit { get; set; } public int Vaba { get; set; } }
which resulted in "Client column not found" error. Progress!_context.Database.SqlQuery<TestResult>($"select 'test', 42, 420").SingleAsync()
- Added column names to correctly match my class definition:
which worked perfectly._context.Database.SqlQuery<TestResult>($"select 'test' \"Client\", 42 \"Credit\", 420 \"Vaba\"").SingleAsync()
Alternative approach with EnableRecordsAsTuples
As suggested by OP in comments, we can use EnableRecordsAsTuples
method to handle that automatically, without need for new class:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(
"connection string",
options =>
{
options.ConfigureDataSource(builder =>
{
builder.EnableRecordsAsTuples();
});
});
base.OnConfiguring(optionsBuilder);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744179007a4561893.html
select s.Value from (<my quey>) s
– Andrus Commented Mar 27 at 6:56