DacFx Получить информацию о столбцах из функцииC#

Место общения программистов C#
Ответить
Anonymous
 DacFx Получить информацию о столбцах из функции

Сообщение Anonymous »

В настоящее время я пытаюсь извлечь тип данных столбца из таблиц, представлений и функций SQL Server на C#, используя DacFx в .NET.
Я хотел бы получить ту же информацию с помощью DacFx который я могу получить с помощью следующего SQL-запроса:

Код: Выделить всё

WITH [PrimaryIndex] AS
(
SELECT
[ic].[object_id],
[ic].[column_id],
[i].[is_primary_key]
FROM
[sys].[index_columns] AS [ic]
JOIN
[sys].[indexes] AS [i] ON [ic].[object_id] = [i].[object_id]
AND [ic].[index_id] = [i].[index_id]
WHERE
[i].[is_primary_key] = 1
)
SELECT
[c].[name] AS [ColumnName],
[t].[name] AS [Datatype],
[c].[max_length] AS [MaxLength],
[c].[precision],
[c].[scale],
[c].[is_nullable],
ISNULL([pri].[is_primary_key], 0) AS [Primary Key],
c.column_id,
c.collation_name
FROM
[sys].[columns] AS [c]
INNER JOIN
[sys].[types] AS [t] ON [c].[user_type_id] = [t].[user_type_id]
LEFT JOIN
[PrimaryIndex] AS [pri] ON [pri].[object_id] = [c].[object_id]
AND [pri].[column_id] = [c].[column_id]
WHERE
c.object_id = OBJECT_ID('DemoSchema.FunctionName')


Имя столбца
Тип данных
Макс.длина
точность
масштаб
is_nullable
Основной Ключ
column_id
Collation_name


< tbody>

Col1
int
4
< td>10
0
1
0
1
NULL


Кол2
дата
3
10
0
0
0
2
NULL


Col3
десятичный
17
38
10
1
0
3
NULL


Col4
десятичный
17
38
10
1
0
4
NULL


Col5
десятичный
17
38
10
1
0
5
NULL


Col6
десятичный
17
38
10
1
0
6
NULL


Col7
десятичный
17
38
10
1
0
7
NULL


Col8
десятичный
17
38
10
1
0
8
NULL



Это мой код C# — мне нужно получить информацию из TableValuedFunction.Columns со следующим кодом.

Код: Выделить всё

 Console.WriteLine($"Load DacPac Content [{dacpacFullPath}]");
var dapacs = Directory.GetFiles(dacpacFullPath, "*.dacpac");
Console.WriteLine($"[{dapacs.Length}] DacPac Found!");
foreach (var dapac in dapacs)
{
var modelFromDacpac = new TSqlModel(dapac);
Console.WriteLine($"LoadDing Current DacPac [{dapac}]");
this.dacPacObjects.AddRange(modelFromDacpac.GetObjects(DacQueryScopes.Default).ToList());
Console.WriteLine($"DacPac  Objects [{this.dacPacObjects.Count}]");
}

// Data type documentation : https://github.com/GoEddie/DacFx-Info/blob/master/DacFxRelationships/ModelSchema.csv
// Look up a specific table by ID.  Note that if no schema is defined when creating
// an element the default "dbo" schema is used
var currentObject = this.dacPacObjects.FirstOrDefault(x => x.Name.Parts.Count >= 2 && $"{x.Name.Parts[0]}.{x.Name.Parts[1]}".ToLower() == fullName.ToLower());
if (currentObject.ObjectType == TableValuedFunction.TypeClass)
{
foreach (var col in currentObject.GetReferenced(TableValuedFunction.Columns, DacQueryScopes.All).ToList())
{
Console.WriteLine("\t" + col.Name);
Console.WriteLine("\tProperties:");
foreach (var property in col.ObjectType.Properties)
{
Console.WriteLine("\t\t" + property.Name + "\t\t" + property.DataType.FullName);
}

Console.WriteLine("\tMetadata:");
foreach (var metaData in col.ObjectType.Metadata)
{
Console.WriteLine("\t\t" + metaData.Name + "\t\t"  + metaData.DataType.FullName);
}

Console.WriteLine($"Precision ->{col.GetProperty(Column.Precision)}");
Console.WriteLine($"Scale->{col.GetProperty(Column.Scale)}");
Console.WriteLine($"Length->{col.GetProperty(Column.Length)}");
}
}

Все равно 0, и я даже не могу получить тип данных столбца.
А это вывод моей консоли:

Код: Выделить всё

Load DacPac Content [E:\DacPac]
[5] DacPac Found!
LoadDing Current DacPac [E:\DacPac\Dac1.dacpac]
DacPac  Objects [318]
LoadDing Current DacPac  [E:\DacPac\master.dacpac]
DacPac  Objects [2743]
LoadDing Current DacPac [E:\DacPac\Dac2.dacpac]
DacPac  Objects [5917]
LoadDing Current DacPac [E:\DacPac\Dac3.dacpac]
DacPac  Objects [11755]
LoadDing Current DacPac [E:\DacPac\Dac4.dacpac]
DacPac  Objects [13640]
[DemoSchema].[FunctionName].[Col1]
Properties:
Collation               System.String
IsIdentityNotForReplication             System.Boolean
Nullable                System.Boolean
IsRowGuidCol            System.Boolean
Sparse          System.Boolean
Expression              Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlScriptProperty
Persisted               System.Boolean
PersistedNullable               System.Nullable`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
Scale           System.Int32
Precision               System.Int32
Length          System.Int32
IsMax           System.Boolean
XmlStyle                Microsoft.SqlServer.Dac.Model.XmlStyle
EncryptionAlgorithmName         System.String
EncryptionType          System.Int32
GeneratedAlwaysType             Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType
GraphType               System.Int32
IdentityIncrement               System.String
IdentitySeed            System.String
IsFileStream            System.Boolean
IsHidden                System.Boolean
IsIdentity              System.Boolean
IsPseudoColumn          System.Boolean
MaskingFunction         System.String
SensitivityInformationType              System.String
SensitivityInformationTypeId            System.String
SensitivityLabel                System.String
SensitivityLabelId              System.String
SensitivityRank         System.Int32
Metadata:
ColumnType              Microsoft.SqlServer.Dac.Model.ColumnType
Precision ->0
Scale->0
Length->0
[DemoSchema].[FunctionName].[Col2]
Properties:
Collation               System.String
IsIdentityNotForReplication             System.Boolean
Nullable                System.Boolean
IsRowGuidCol            System.Boolean
Sparse          System.Boolean
Expression              Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlScriptProperty
Persisted               System.Boolean
PersistedNullable               System.Nullable`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,  PublicKeyToken=7cec85d7bea7798e]]
Scale           System.Int32
Precision               System.Int32
Length          System.Int32
IsMax           System.Boolean
XmlStyle                Microsoft.SqlServer.Dac.Model.XmlStyle
EncryptionAlgorithmName         System.String
EncryptionType          System.Int32
GeneratedAlwaysType             Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType
GraphType               System.Int32
IdentityIncrement               System.String
IdentitySeed            System.String
IsFileStream            System.Boolean
IsHidden                System.Boolean
IsIdentity              System.Boolean
IsPseudoColumn          System.Boolean
MaskingFunction         System.String
SensitivityInformationType              System.String
SensitivityInformationTypeId            System.String
SensitivityLabel                System.String
SensitivityLabelId              System.String
SensitivityRank         System.Int32
Metadata:
ColumnType              Microsoft.SqlServer.Dac.Model.ColumnType
Precision ->0
Scale->0
Length->0
etc...

Я также пытаюсь изучить массу данных на двух следующих веб-сайтах:
https://the.agilesql.club/2019/04/dacfx-how-to-get -тип-данных-из-столбца-обсуждение-свойств-отношений-и-модели-tsql/
https://sqlserverfunctions.wordpress.co ... formation/
Но они оба относятся к типу Table.Columns, а не к типу TableValuedFunction.Columns
Есть ли решение для получения этой информации из Дакпак? Или мне следует пропустить эту опцию и получить данные из SQL (я бы хотел избежать этого шага).
Заранее спасибо.

Подробнее здесь: https://stackoverflow.com/questions/793 ... m-function
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»