开发者

EF4.1 Code First: How to set the name of the index/pk database object?

开发者 https://www.devze.com 2023-04-01 09:51 出处:网络
Code first EF gene开发者_如何学JAVArates primary key and index objects without names. Sql Server in turn auto generates names for these objects on the form:

Code first EF gene开发者_如何学JAVArates primary key and index objects without names. Sql Server in turn auto generates names for these objects on the form:

PK__Invitati__033C8DCF03317E3D

I can't find a code first way of setting this to something nicer, such as PK_Invitation, is it not possible?

Thanks!


There is no way. If you want to change it you must create custom database initializer which will find created PKs, drop them and create them again with your own names. Here is the example using the similar approach to change default constraint.


I ended up using SMO to rename the primary keys. Full blog write-up available here; including this code snippet:

  // 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();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消