This is a migrated thread and some comments may be shown as answers.

Can't cast System.Data.SqlClient.SqlParameter into NpgsqlParameter

1 Answer 1300 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Jonorou
Top achievements
Rank 1
Jonorou asked on 02 Feb 2016, 04:30 AM

How to use ExecuteQuery with DbParameter in Postgresql?

I got this error "Can't cast System.Data.SqlClient.SqlParameter into NpgsqlParameter", when execute query with parameter. 

System.Data.Common.DbParameter[] parameters = new[]{
        new System.Data.SqlClient.SqlParameter(){ ParameterName="ParamName", Value="Cloon" },
};

repo.ExecuteQuery<User>("SELECT * FROM Users Where name = :ParamName", parameters);

1 Answer, 1 is accepted

Sort by
0
William John Adam
Top achievements
Rank 1
answered on 02 Feb 2016, 06:30 PM

You can't use SQLClient Parameters with NPGSQL. Npg has its own NameSpace Parameters.. se an exemple(source):

using System;
using System.Data;
using Npgsql;
 
public static class NpgsqlUserManual
{
    public static void Main(String[] args)
    {
        using(NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;"))
        {
            conn.Open();
 
            // Declare the parameter in the query string
            using(NpgsqlCommand command = new NpgsqlCommand("select * from tablea where column1 = :column1", conn))
            {
                // Now add the parameter to the parameter collection of the command specifying its type.
                command.Parameters.Add(new NpgsqlParameter("column1", NpgsqlDbType.Integer);
 
                // Now, prepare the statement.
                command.Prepare();
 
                // Now, add a value to it and later execute the command as usual.
                command.Parameters[0].Value = 4;
 
                using(NpgsqlDataReader dr = command.ExecuteReader())
                {
                    while(dr.Read())
                    {
                        for (i = 0; i < dr.FieldCount; i++)
                        {
                            Console.Write("{0} \t", dr[i]);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
    }
}

Tags
Development (API, general questions)
Asked by
Jonorou
Top achievements
Rank 1
Answers by
William John Adam
Top achievements
Rank 1
Share this question
or