如何从 C# 中的数据库模式获取列的默认值?

How to get DefaultValue of column from database schema in C#?

我正在尝试从我的 C# 数据库模式(.NET 4.5,SQL Server 2014)中读取信息。在我 found a forum 提到将 DataAdapter.MissingSchemaAction 设置为 MissingSchemaAction.AddWithKey 之前,我在处理 MaxLength/ColumnLength 等某些字段时遇到了麻烦。不幸的是,即使对于在 SQL 服务器的列属性的 "Default Value or Binding" 中设置了默认值的列,DefaultValue 字段仍然是空白。

SqlDataAdapter dbadapter = new SqlDataAdapter(SELECT_STRING, CONN_STRING);
dbadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataTable tbl = new DataTable();
dbadapter.Fill(tbl);

// I actually looped through all rows/columns, but the net effect here is...
tbl.Columns[0].DefaultValue; // blank for all columns

// Also tried accessing the schema table available through DataReader
IDataReader reader = tbl.CreateDataReader();
DataTable schemaTbl = reader.GetSchemaTable();
/*
 * There are different schema fields here than in DataColumn,
 * but DefaultValue still blank. I looped through them all but...
 */
schemaTbl.Rows[0]["DefaultValue"]; // blank for all columns

如何使用 .NET 从我的 table 中的列中读取默认值(最好不求助于查询 SQL 的 sys.* tables) .

澄清

创建或更改 table 时,如果提供了 none,您可以设置列的默认值。我正在尝试获取默认值。

示例:

CREATE TABLE Person
(
    Id int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    HomeState varchar(2) DEFAULT 'NY'
)

现在如果我说,INSERT INTO Person (Id, LastName, FirstName) VALUES (1, 'Doe', 'John') HomeState 将是 'NY',即使我没有设置它。

尝试使用 Microsoft.SqlServer.Smo 库,如下所示:

using (var connection = new SqlConnection("connectionString"))
{
    var serverConnection = new ServerConnection(connection);
    var server = new Server(serverConnection);
    var database = server.Databases["databaseName"];
    var table = database.Tables["tableName"];

    foreach (Column column in table.Columns)
    {
        Console.WriteLine($"{column.Name} - default constraint: {column.DefaultConstraint?.Text ?? "None"}");
    }
    Console.ReadLine();
}

编辑

感谢@Crowcoder 建议进行以下简化:

var serverConnection = new ServerConnection("serverName", "username", "password");
var server = new Server(serverConnection);
var database = server.Databases["databaseName"];
var table = database.Tables["tableName"];

foreach (Column column in table.Columns)
{
    Console.WriteLine($"{column.Name} - default constraint: {column.DefaultConstraint?.Text ?? "None"}");
}
Console.ReadLine();