ASP.NET Core 1 RC2 - 数据库架构

时间:2016-05-24 07:32:54

标签: c# asp.net-core asp.net-core-1.0

有人可以建议如何在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

        }

2 个答案:

答案 0 :(得分:2)

因为它返回了已经折旧的connection.GetSchema,所以DataTable已在Asp.Net Core中折旧。现在这样做的方法是打开运行ExecuteReader()函数,然后使用生成的reader对象中的GetSchemaColumn()函数。

以下是一个示例:

    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();
    }

注意:我认为这在Rc2中仍然是稳定的。例如,column.IsKey函数始终返回null。

答案 1 :(得分:0)

如果你需要数据库中的所有表名,我设法做到了:

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;
}