代碼優先EF生成沒有名稱的主鍵和索引對象。反過來自動SQL Server作爲形式對這些對象生成的名字:EF4.1代碼優先:如何設置索引/ pk數據庫對象的名稱?
PK__Invitati__033C8DCF03317E3D
我找不到這個設置的東西更好,如PK_Invitation的代碼第一種方式,是不可能的?
謝謝!
代碼優先EF生成沒有名稱的主鍵和索引對象。反過來自動SQL Server作爲形式對這些對象生成的名字:EF4.1代碼優先:如何設置索引/ pk數據庫對象的名稱?
PK__Invitati__033C8DCF03317E3D
我找不到這個設置的東西更好,如PK_Invitation的代碼第一種方式,是不可能的?
謝謝!
有沒有辦法。如果你想改變它,你必須創建自定義的數據庫初始化工具,它會找到創建的PK,放下它們並用你自己的名字重新創建它們。 Here is the example使用類似的方法來更改默認約束。
我結束了使用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();
}
不幸的是,知道這是不可能的,非常有用,謝謝! –