简体   繁体   中英

ASP.NET Core 1 RC2 - database schema

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.

If you need all table names from a database I managed to do this:

public List<string> getTables()
{
    List<string> result = new List<string>();
    using (SqlConnection connection = new SqlConnection(appSettings.ConnectionStringSamples))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("SELECT name FROM sys.Tables;", connection))
        using (SqlDataReader reader = command.ExecuteReader())
        while (reader.Read()) result.Add(reader["name"].ToString());
    }

    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM