我在 T-SQL 中有几个存储过程,其中每个存储过程都有一个固定的结果集架构。
我需要将每个过程的结果集映射到 POCO 对象,并且需要结果集中每列的列名称和类型。有没有快速获取信息的方法?
到目前为止,我发现的最好方法是从 .NET 访问每个存储过程,并在 IDataReader/IDataRecord 上编写我自己的扩展方法,以转储信息(列名称和类型)。
例如,执行以下查询的存储过程:
SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable
需要我提供映射信息:
Id - Guid
IntField - System.Int32
NullableIntField - Nullable<System.Int32>
VarcharField - String
DateField - DateTime
我想你应该能够使用SqlDataReader.GetSchemaTable访问模式的方法。
更多信息可以在这里找到。
http://support.microsoft.com/kb/310107 http://support.microsoft.com/kb/310107
上述来源的示例
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataTable schemaTable;
SqlDataReader myReader;
//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = "Data Source=server;User ID=login;
Password=password;Initial Catalog=DB";
cn.Open();
//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable";
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
//Retrieve column schema into a DataTable.
schemaTable = myReader.GetSchemaTable();
//For each field in the table...
foreach (DataRow myField in schemaTable.Rows){
//For each property of the field...
foreach (DataColumn myProperty in schemaTable.Columns) {
//Display the field name and value.
Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
}
Console.WriteLine();
//Pause.
Console.ReadLine();
}
//Always close the DataReader and connection.
myReader.Close();
cn.Close();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)