I am attempting to read extended properties on tables and columns in a winforms C# application. I am using SQL Server SMO to do so. When I execute the application it does not see the extended properties, but when I read the extended properties using PowerShell, it does see the extended properties.
The C# code:
var x = col.ExtendedProperties.Count;
var NPI = col.ExtendedProperties["NPI"].Value;
bool npi = bool.Parse(NPI.ToString());
The PowerShell code:
Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $env:COMPUTERNAME
$server.Databases["<db name>"].Tables["<table name>"].Columns["<column name>"].ExtendedProperties | Select Name, Value, State
I have checked and both Visual Studio and PowerShell are using the same version of SMO (11.0.0.0). When I execute the C# code the col.ExtendedProperties.Count = 0, but when I execute the PowerShell code I get:
Name Value State
---- ----- -----
NPI False Existing
Does anyone have any ideas as to why this could be happening?
Additional Information
In the C# code I open up a DataReader on a table using:
sourceServer.ConnectionContext.ExecuteReader(<select command>)
to retrieve the data from the table. I then go into a while loop with DataReader and inside that while loop I have:
foreach (Column col in sourceTable.Columns)
{
StringBuilder cleanData = CleanseColumn(col, dr[col.Name].ToString());
sbvalues.Append("'" + cleanData + "', ");
}
When I step through the foreach
, the sourceTable
variable has its extended property, but the col
column variable does not.
Best Answer
I just want to shadow @BradC a little. I tested his code on Visual Studio 2015 (Update 3) on a Windows 10 Pro x64 machine against an SQL Server 2014 instance and I can confirm you can get Extended Properties of a field without issues.
To replicate I use one of my local databases. I used the following code snip to define some extended properties.
I created a new console project and added the following references:
All from:
So my whole code, based on @BradC's looks like:
Of course you can now access the properties and use their values.
The Count value that wasn't working on your example: