sql-serversql-server-data-toolsdac

How to get Type of a column using DacFx api?


In SSDT project, using DacFx API, I am querying in memory model of a database. I have been trying to retrieve Type of a column, but cannot figure it out. Any idea how this could be done?

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

Solution

  • Without using the strongly-typed model, it'd be:

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

    The strongly-typed model can make this easier, though. Check out https://github.com/Microsoft/DACExtensions/tree/master/DacFxStronglyTypedModel