ASP.NET使用LINQ调用存储过程并传入DataTable

时间:2010-12-07 15:11:26

标签: asp.net linq stored-procedures datatable

我做错了什么? 尝试使用LINQ将我的DataTable传递给存储过程。以下是我的代码。

var sqlCommand = new System.Data.SqlClient.SqlCommand {
    CommandType = System.Data.CommandType.StoredProcedure,
    CommandText = "UserIdList"
};

var dataTable = new System.Data.DataTable("IdList");
dataTable.Columns.Add("AttributeIds", typeof(Int32));
dataTable.Rows.Add(26);
dataTable.Rows.Add(40);
dataTable.Rows.Add(41);
dataTable.Rows.Add(45);
dataTable.Rows.Add(78);
dataTable.Rows.Add(33);
dataTable.Rows.Add(36);

//The parameter for the SP must be of SqlDbType.Structured 
var parameter = new System.Data.SqlClient.SqlParameter { 
    ParameterName = "@AttributeIds",
    SqlDbType = System.Data.SqlDbType.Structured,
    TypeName =  "ecs.IDList",
    Value = dataTable,
};

sqlCommand.Parameters.Add(parameter);

var user = myDC.DC.ExecuteQuery("exec ecs.udpUserAttributeDetails {0}, {1}", sqlCommand, userId).SingleOrDefault();


1 个答案:

答案 0 :(得分:1)

这似乎是问题

var user = myDC.DC.ExecuteQuery("exec ecs.udpUserAttributeDetails {0}, {1}", sqlCommand, userId).SingleOrDefault();

在您的代码中,您将sqlCommand对象作为第一个参数传递,将userId作为第二个参数传递。

数据上下文ExecuteQuery method has 2 overloads

ExecuteQuery<TResult>(String, Object[]) 
ExecuteQuery(Type, String, Object[])

您似乎正在使用重载1 - 即ExecuteQuery<TResult>(String, Object[])但在这种情况下您需要指定返回对象的类型

例如: -

 var customers = db.ExecuteQuery<Customer>(@"SELECT CustomerID, CompanyName, ContactName FROM dbo.Customers WHERE  City = {0}", "London");

注意:上面示例中的 db.ExecuteQuery <Customer>就是我所指的。

我认为这可能是错误的原因,因为编译器将您的请求映射到重载2而不是返回任何值但接收3个参数导致您的A query parameter cannot be of type 'System.Data.SqlClient.SqlCommand错误。

相关问题