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

2 posts, 0 answers
  1. Jonorou
    Jonorou avatar
    1 posts
    Member since:
    Apr 2013

    Posted 01 Feb Link to this post

    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);

  2. William John Adam Trindade
    William John Adam Trindade avatar
    3 posts
    Member since:
    Apr 2010

    Posted 02 Feb in reply to Jonorou Link to this post

    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();
                        }
                    }
                }
            }
        }
    }

  3. DevCraft banner
Back to Top