2011-08-31 73 views

回答

2

有没有办法。如果你想改变它,你必须创建自定义的数据库初始化工具,它会找到创建的PK,放下它们并用你自己的名字重新创建它们。 Here is the example使用类似的方法来更改默认约束。

+0

不幸的是,知道这是不可能的,非常有用,谢谢! –

0

我结束了使用SMO重命名主键。完整的博客写作available here;包括此代码片段:

// Get a Server object from the existing connection 
    var server = new Microsoft.SqlServer.Management.Smo.Server(
    new Microsoft.SqlServer.Management.Common.ServerConnection 
     (context.Database.Connection as System.Data.SqlClient.SqlConnection)); 
    // Get a database object. Qualify names to avoid EF name clashes. 
    Microsoft.SqlServer.Management.Smo.Database database = 
    server.Databases[context.Database.Connection.Database]; 

    // Rename auto generated primary key names 
    (
    from Microsoft.SqlServer.Management.Smo.Table table in database.Tables 
    where table.Schema == "WebApp" 
    from Microsoft.SqlServer.Management.Smo.Index index in table.Indexes 
    where index.IndexKeyType == 
     Microsoft.SqlServer.Management.Smo.IndexKeyType.DriPrimaryKey 
    // Create pairs of a name string and an Index object 
    select new { table.Name, index } 
    // ToList() separates reading the object model above from modifying it below 
).ToList() 
    // Use extension and anonymous methods to rename the primary keys 
    .ForEach(primaryKey => 
    { 
     // Name primary keys "PK_TableName" 
     primaryKey.index.Rename(
     "PK_" + primaryKey.Name.Replace("[", "").Replace("]", "")); 
     primaryKey.index.Alter(); 
    } 
相关问题