PHe*_*erg 9 .net c# t-sql sql-server
我在T-SQL中有几个存储过程,其中每个存储过程都有一个固定的结果集模式.
我需要将每个过程的结果集映射到POCO对象,并且需要结果集中每列的列名和类型.有快速访问信息的方法吗?
到目前为止,我发现的最好的方法是从.NET访问每个存储过程,并在IDataReader/IDataRecord上编写我自己的扩展方法,以便转储信息(列名和类型).
例如,执行以下查询的存储过程:
SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable
Run Code Online (Sandbox Code Playgroud)
会要求我有映射信息:
Id - Guid
IntField - System.Int32
NullableIntField - Nullable<System.Int32>
VarcharField - String
DateField - DateTime
Run Code Online (Sandbox Code Playgroud)
Ami*_*abh 10
我认为您应该能够使用SqlDataReader.GetSchemaTable方法来访问架构.
更多信息可以在这里找到.
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4274 次 |
| 最近记录: |