Jonathan Allen
Jonathan Allen

Reputation: 70327

Is there a library for reading DACPAC files?

I would like to read the contents of a DACPAC in order to get the list of schema, tables, etc.

Upvotes: 2

Views: 470

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300749

Yes. You can use DacFx for this.

DacFx Public Model Tutorial:

  // Load from a dacpac
  using (TSqlModel modelFromDacpac = new TSqlModel("mydb.dacpac"))
  {        
      ReadTheModel(modelFromDacpac);
  }

 private static void ReadTheModel(TSqlModel model)
 {
     // This will get all tables. Note the use of Table.TypeClass!
     var tables = model.GetObjects(DacQueryScopes.Default, Table.TypeClass).ToList();

     // 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 t1 = model.GetObjects(Table.TypeClass, 
         new ObjectIdentifier("dbo", "t1"), DacQueryScopes.Default).FirstOrDefault();

      // Get a the column referenced by this table, and query its length 
      TSqlObject column = t1.GetReferenced(Table.Columns)
              .First(col => col.Name.Parts[2].Equals("c1"));

      int columnLength = column.GetProperty<int>(Column.Length);
      Console.WriteLine("Column c1 has length {0}", columnLength); 


      // Verify the ColumnType of this column. This can help indicate which 
      // properties will return meaningful values.
      // For instance since Column.Collation is only available on a simple column,
      // and Column.Persisted is only on computed columns
      ColumnType columnType = column.GetMetadata<ColumnType>(Column.ColumnType);
      Console.WriteLine("Column c1 is of type '{0}'", columnType);
  } 

Upvotes: 4

Related Questions