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

时间:2017-05-18 22:23:24

标签: sql-server sql-server-data-tools dac

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

2 个答案:

答案 0 :(得分:1)

不使用强类型模型,它是:

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

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

答案 1 :(得分:0)

正确的代码应该是:

string dataType = col.DataType;