如何使用 DacFx api 获取列的类型?

How to get Type of a column using DacFx api?

在 SSDT 项目中,使用 DacFx API,我在数据库的内存模型中查询。我一直在尝试检索列的类型,但无法弄清楚。知道如何做到这一点吗?

   private void TestMethod()
        {
            using(TSqlModel model = 
                new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions {}))
            {
                string[] scripts = new[]
                {
                    "CREATE TABLE t1 (c1 NVARCHAR(30) NOT NULL)",
                    "CREATE TABLE t2 (c2 INT NOT NULL)"
                };
                foreach (string script in scripts)
                {
                    model.AddObjects(script);
                }

                var tables = model.GetObjects(DacQueryScopes.All, Table.TypeClass);
                var cols = tables.First().GetReferenced(Table.Columns);
                foreach (TSqlObject col in cols)
                {
                    //?? how can I get the data type of the column?
                    string dataType = col.??; 
                    if (dataType == "int")
                    {
                        //my thing here
                    }
                }
            }
        }

正确的代码应该是:

string dataType = col.DataType;

如果不使用强类型模型,它将是:

var dataType = col.GetReferenced(Column.DataType).First();
var dataTypeName = dataType.Name.Parts[0];

不过,强类型模型可以使这更容易。查看 https://github.com/Microsoft/DACExtensions/tree/master/DacFxStronglyTypedModel