如果有人仍然对此主题感兴趣,我会在这里写下我的解决方案。
下面的代码更改了 add-migration 命令的输出。
public class CustomMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(CreateTableOperation createTableOperation, IndentedTextWriter writer)
{
if (createTableOperation.Columns.Any(x => x.Name == "Index") &&
createTableOperation.Columns.Any(x => x.Name == "Id"))
{
if (createTableOperation.PrimaryKey != null)
{
createTableOperation.PrimaryKey.IsClustered = false;
}
}
base.Generate(createTableOperation, writer);
}
}
您可以在迁移配置中注册此生成器:
internal sealed class Configuration : DbMigrationsConfiguration<Ubrasoft.Freeman.WebApi.Db.MainDb>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
CodeGenerator = new CustomMigrationCodeGenerator();
SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());
}
protected override void Seed(Ubrasoft.Freeman.WebApi.Db.MainDb context)
{
}
}
这里是生成的迁移代码:
public override void Up()
{
CreateTable(
"Tenant.Tenant",
c => new
{
Id = c.Guid(nullable: false),
TenantNo = c.Byte(nullable: false),
Name = c.String(nullable: false, maxLength: 20),
Index = c.Int(nullable: false, identity: true),
CreatedDate = c.DateTime(nullable: false, precision: 0, storeType: "datetime2"),
UpdatedDate = c.DateTime(nullable: false, precision: 0, storeType: "datetime2"),
IsDeleted = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id, clustered: false)
.Index(t => t.Index, unique: true, clustered: true);
}
Here 是关于自定义 MigrationCodeGenerator 的文章。