0

Code first EF generates 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!

Kristian Wedberg
  • 465
  • 4
  • 10

2 Answers2

2

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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
0

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();
    }
Kristian Wedberg
  • 465
  • 4
  • 10