代码优先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();
}
不幸的是,知道这是不可能的,非常有用,谢谢! –