我尝试自定义EF生成的SQL中的主键名称。我已经通过剥离架构名称成功地自定义了外键。但是,当我对主键使用相同的技术时,它似乎不起作用。
这是我使用的生成器类:
public class KeyNamingGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(DropForeignKeyOperation dropForeignKeyOperation)
{
dropForeignKeyOperation.Name = StripSchema(dropForeignKeyOperation.Name);
base.Generate(dropForeignKeyOperation);
}
protected override void Generate(DropPrimaryKeyOperation dropPrimaryKeyOperation)
{
dropPrimaryKeyOperation.Name = StripSchema(dropPrimaryKeyOperation.Name);
base.Generate(dropPrimaryKeyOperation);
}
protected override void Generate(AddForeignKeyOperation addForeignKeyOperation)
{
addForeignKeyOperation.Name = StripSchema(addForeignKeyOperation.Name);
base.Generate(addForeignKeyOperation);
}
protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
{
addPrimaryKeyOperation.Name = StripSchema(addPrimaryKeyOperation.Name);
base.Generate(addPrimaryKeyOperation);
}
private string StripSchema(string name)
{
return Regex.Replace(name, @"(?<=_)[a-zA-Z]*\.", "", RegexOptions.Compiled);
}
}
与外键相关的Generate方法工作正常,但与Primary Key相关的方法并不适用。我错过了什么?
答案 0 :(得分:0)
事实证明,AddPrimaryKeyOperation仅在您独立于表创建添加PK时才有效。一时兴起,我决定深入研究CreateTableOperation,它有一个可以操作的PrimaryKey属性。
以下是完成的代码:
protected override void Generate(CreateTableOperation createTableOperation)
{
createTableOperation.PrimaryKey.Name = StripSchema(createTableOperation.PrimaryKey.Name);
base.Generate(createTableOperation);
}
有关如何使用SqlServerMigrationSqlGenerator的几个例子并没有真正解决这个问题。