Can somebody advise how to get the schema in ASP.NET Core 1 RC2?
using (SqlConnection connection = new SqlConnection("Server=.;Database=Mydb;Trusted_Connection=True;MultipleActiveResultSets=true"))
{
connection.Open();
connection.GetSchema("Tables"); // doesn't work
}
The connection.GetSchema
has been depreciated in Asp.Net Core due as it returns the DataTable
which has also been depreciated. The way to do this now is is to open run the ExecuteReader()
function, and then use the GetSchemaColumn()
function from the resulting reader object.
Here is a sample:
public static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection("Server=(localdb)\\v11.0;Database=MyAdventureWorks;Trusted_Connection=True"))
{
connection.Open();
SqlCommand cmd = new SqlCommand("select * from [Person].[Person]", connection);
DbDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SchemaOnly);
if (reader.CanGetColumnSchema())
{
var columns = reader.GetColumnSchema();
foreach (var column in columns)
{
Console.Write("ColumName: " + column.ColumnName);
Console.Write(", DataTypeName: " + column.DataTypeName);
Console.Write(", ColumnSize: " + column.ColumnSize);
Console.WriteLine(", IsUnique: " + column.IsUnique);
}
}
else
throw new Exception("Connection does not support GetColumnSchema.");
}
Console.ReadLine();
}
Note: I think this is still be stabalized in Rc2. For example the column.IsKey function always returning null.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments