I have a database created through code first approach and all the pk, fk and index names are created with dbo.
, for example PK_dbo.VendorID
and I would like them to be PK_VendorID
same with fk's and index names.
I have followed these approaches:
First approach:
Visit How can I stop Entity Framework 5 migrations adding dbo. into key names?
When I run the update-database
command it asks me to disable the automatic migration and also enable the data loss but my projects will do automatic migrations ...
Second approach:
Visit How to Specify Primary Key Name in EF-Code-First
I am able to achieve by using sp_rename
, but I have many changes to pk, fk and index names ..
Please let me know how I can strip off the dbo.
prefix from pk, fk and index names. I am beginner in coding.
public class MigrationSqlGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(DropIndexOperation dropIndexOperation, IndentedTextWriter writer)
{
dropIndexOperation.Table = StripDbo(dropIndexOperation.Table);
base.Generate(dropIndexOperation, writer);
}
//protected override void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer)
//{
// addForeignKeyOperation.Name = this.StripDbo(addForeignKeyOperation.Name, addForeignKeyOperation.DependentTable);
// addForeignKeyOperation.Name = this.StripDbo(addForeignKeyOperation.Name, addForeignKeyOperation.PrincipalTable);
// base.Generate(addForeignKeyOperation, writer);
//}
//protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
//{
// addPrimaryKeyOperation.Name = StripDbo(addPrimaryKeyOperation.Name, addPrimaryKeyOperation.Table);
// base.Generate(addPrimaryKeyOperation, writer);
//}
//protected override void Generate(DropForeignKeyOperation dropForeignKeyOperation, IndentedTextWriter writer)
//{
// dropForeignKeyOperation.Name = this.StripDbo(dropForeignKeyOperation.Name, dropForeignKeyOperation.DependentTable);
// dropForeignKeyOperation.Name = this.StripDbo(dropForeignKeyOperation.Name, dropForeignKeyOperation.PrincipalTable);
// base.Generate(dropForeignKeyOperation, writer);
//}
//protected override void Generate(DropPrimaryKeyOperation dropPrimaryKeyOperation, IndentedTextWriter writer)
//{
// dropPrimaryKeyOperation.Name = StripDbo(dropPrimaryKeyOperation.Name, dropPrimaryKeyOperation.Table);
// base.Generate(dropPrimaryKeyOperation, writer);
//}
//private string StripDbo(string objectName, string tableName)
//{
// if (tableName.StartsWith("dbo."))
// {
// return objectName.Replace(tableName, tableName.Substring(4));
// }
// return objectName;
//}
// TODO: Override other Generate overloads that involve table names
private string StripDbo(string table)
{
if (table.StartsWith("dbo."))
{
return table.Substring(4);
}
return table;
}
}
- FromName:
PK_dbo.VendorID
- ToName:
PK_VendorID