aleczandru
aleczandru

Reputation: 5459

ExecuteNonQuery results in a Parameter mapping error

Hi I am trying to insert data to a database using ADO.NET.Here is my code. This is my C# code:

 public void CreateBook(FormCollection collection)
        {
            string name = collection["BookName"];
            string author = collection["Author"];
            string description = collection["Description"];
            int category = int.Parse(collection["category"]);
            DateTime currentDate = new DateTime();

            using (SqlConnection connection = new SqlConnection(connectionString)) {
                connection.Open();
                SqlCommand command = new SqlCommand("AddBook", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add(createParameter(name, "@Name"));
                command.Parameters.Add(createParameter(author, "@Author"));
                command.Parameters.Add(createParameter(description, "@Description"));
                command.Parameters.Add(createParameter(currentDate.Date, "@Date"));
                command.Parameters.Add(createParameter(category, "@CategoryId"));
                command.ExecuteNonQuery();
            }
        }
        //there are 2 other overloads of this method
        private SqlParameter createParameter(string parameter , string parameterName) {
            SqlParameter param = new SqlParameter();
            param.ParameterName = parameterName;
            param.Value = param;
            return param;
        }

And this is my SQL code:

 CREATE PROCEDURE [dbo].[AddBook]
    @Name nvarchar(MAX),
    @Author nvarchar(MAX),
    @Description nvarchar(MAX),
    @Date date  ,
    @CategoryId int
 AS
    INSERT INTO Books (Name , Author , Description , PublicationDate , CategoryId)
    VALUES (@Name , @Author , @Description , @Date , @CategoryId)

When ExecuteNonQueryuery is being fired I get this error:

No mapping exists from object type System.Data.SqlClient.SqlParameter to a known managed provider native type. 

What am I doing wrong?

Upvotes: 2

Views: 2763

Answers (2)

NDJ
NDJ

Reputation: 5194

you're assigning the actual parameter to the parameter - param.Value = param;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503090

I suspect this line is the most immediate problem:

param.Value = param;

You meant:

param.Value = parameter;

Otherwise you're trying to set the parameter value to the parameter itself, which is meaningless.

However, I would personally recommend specifying the type etc as well. You can get rid of your other methods, and just use calls like this:

command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = name;
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = currentDate.Date;
// etc

Upvotes: 5

Related Questions