kus
I am trying to use npgsql with .net core and I get this error.
If this is not enough information, I can add more of the code here.
the complete repo is at https://github.com/9034725985/pokerleaderboard
Thank you!
> 42804: column "winnings" is of type numeric but expression is of type text
This is my create table
```sql
create table lookup_country
(
id integer primary key generated always as identity,
external_id varchar(255) default gen_random_uuid() unique not null,
full_name varchar(255) unique not null,
abbreviation varchar(10) unique not null
);
create table person
(
id integer primary key generated always as identity,
external_id varchar(255) default gen_random_uuid() unique not null,
full_name varchar(255) not null,
winnings decimal(19,4) not null default 0,
country varchar(255) not null references lookup_country (external_id)
);
```
and this is my C# code
```
public static async void AddPerson(string connectionString, string fullName, decimal winnings, string countryAbbreviation)
{
await using var conn = new NpgsqlConnection(connectionString: connectionString);
await conn.OpenAsync();
try
{
await using (var cmd = new NpgsqlCommand(@"
insert into person(full_name, winnings, country)
select person_name, winnings, external_id
from
(
values
('@fullName', '@winnings')
) as person (person_name, winnings)
cross join (select external_id from lookup_country where abbreviation = '@abbreviation') c;", conn))
{
cmd.Parameters.AddWithValue("full_name", fullName);
cmd.Parameters.AddWithValue("winnings", winnings);
cmd.Parameters.AddWithValue("abbreviation", countryAbbreviation);
await cmd.ExecuteNonQueryAsync();
}
} catch (Exception e)
{
Console.WriteLine(e.Message, e);
}
}
```
I am missing something (I think pretty small) but I don't know what... any ideas?
Top Answer
FoggyFinder
There are couple things:
1. You have to pass all necessary parameters in a insert query. Since the method takes `countryAbbreviation` and not its id the additional subquery is required:
```
var sql = @"
insert into person(full_name, winnings, country)
values(@fullName, @winnings,
(select external_id from lookup_country
where abbreviation = @abbreviation))";
await using (var cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("fullName", fullName);
cmd.Parameters.AddWithValue("winnings", winnings);
cmd.Parameters.AddWithValue("abbreviation", countryAbbreviation);
await cmd.ExecuteNonQueryAsync();
}
```
2. The `Get` method currently doesn't work properly since there is a typo in the constructor:
```
public Person(int id, Guid externalId, string fullName, decimal winnings, LookupCountry country)
{
Id = id;
ExternalId = externalId;
FullName = fullName;
Winnings = Winnings;
Country = country;
}
```
[here](https://github.com/9034725985/pokerleaderboard/blob/master/PokerLeaderboardBackend/PokerLeaderboard.BusinessLogic/Person.cs#L17)
It should be
```
Winnings = winnings;
```