Question

I am currently creating a database like this :

var database = new server(serverconnection blah blah);
var table = new Table(database, "tablename");

var name = new Column(tab, "Name", DataType.NVarChar(255));
tab.Columns.Add(name);

var something = new Column(tab, "Something", DataType.NVarChar(255));
tab.Columns.Add(something);

But now lets say I wanted to add an autoincrementing column? I noticed there was an IndexedColumn but it doesn't say anything about autoincrementing.

Does anyone know how to accomplish autoincrementing with Sqlserver.Management.Smo? I'm not interested in a query for this, I want to do it using Smo.

Was it helpful?

Solution

You are looking for an 'identity column'. Something like this should work:

// Add ‘ID’ column which is the primary key
Column idColumn = new Column(table, "ID");
idColumn.DataType = DataType.Int;
idColumn.Identity = true;
idColumn.IdentitySeed = 1;
idColumn.IdentityIncrement = 1;

// Create a primary key index
Index index = new Index(table, string.Format("PK_{0}", table.Name));
index.IndexKeyType = IndexKeyType.DriPrimaryKey;
index.IndexedColumns.Add(new IndexedColumn(index, "ID"));
table.Indexes.Add(index);


// Add colums to table
table.Columns.Add(idColumn);

example code from this blog/article: http://www.christophdebaene.com/blog/2007/12/31/programmatically-creating-tables-in-sql-server-using-net-and-smo/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top