2011-08-31 75 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(); 
    } 
相關問題