2013-02-26 66 views
2

嗨我試圖插入數據到數據庫使用ADO.NET.Here是我的代碼。 這是我的C#代碼:ExecuteNonQuery結果參數映射錯誤

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

,這是我的SQL代碼:

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) 

當ExecuteNonQueryuery被解僱我得到這個錯誤:

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

我在做什麼錯?

+0

只是提示:你不需要創建一個像'createParameter'這樣的方法。在'Parameters.Add()'方法中使用'new SqlParameter()'。 IMO更清晰簡單.. – 2013-02-26 13:35:01

回答

5

我懷疑這條線是最直接的問題:

param.Value = param; 

您的意思是:

param.Value = parameter; 

否則你試圖設置參數的參數本身,這是無意義的。

但是,我個人建議指定類型等。你可以擺脫你的其他方法,並使用這樣的調用:

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

你正在分配參數的實際參數 - param.Value = param;