Я использую ядро Entity Framework для SQL Server и PostgreSQL.
И мне нужно переопределить создание индекса с помощью столбцов include.
Я использую NpgsqlMigrationsAnnotationProvider и NpgsqlMigrationsSqlGenerator для этого.
Мой код
NpgsqlMigrationsSqlGenerator
Генерация функции:
base.Generate(operation, model, builder, false);
System.Diagnostics.Debugger.Launch();
var includeIndexAnnotation = operation.FindAnnotation("IncludeIndex");
if (includeIndexAnnotation != null)
{
var includeColumns = includeIndexAnnotation.Value.ToString().Split(",");
var includeOperation = new StringBuilder();
builder.Append(" INCLUDE(");
foreach (var includeColumn in includeColumns)
{
if (includeOperation.Length > 0)
includeOperation.Append(",");
includeOperation.Append($"\"{includeColumn}\"");
}
includeOperation.Append(")");
builder.Append(includeOperation);
}
if (terminate)
{
builder.AppendLine(StatementTerminator);
EndStatement(builder);
}
И
NpgsqlMigrationsAnnotationProvider
Для (IIndex index) функция:
var baseAnnotations = base.For(index);
var customAnnotations = index.GetAnnotations().Where(a => a.Name == "IncludeIndex");
return baseAnnotations.Concat(customAnnotations);
Расширения:
public static IndexBuilder Include<TEntity>(this IndexBuilder indexBuilder, Expression<Func<TEntity, object>> indexExpression)
{
var includeStatement = new StringBuilder();
foreach (var column in indexExpression.GetPropertyAccessList())
{
if (includeStatement.Length > 0)
includeStatement.Append(",");
includeStatement.AppendFormat("{0}", column.Name);
}
indexBuilder.HasAnnotation("IncludeIndex", includeStatement.ToString());
return indexBuilder;
}
DesignTimeDbContextFactory:
builder.ReplaceService<IMigrationsAnnotationProvider, PostgreSql.DbMigrationsAnnotationProvider>();
builder.ReplaceService<IMigrationsSqlGenerator, PostgreSql.DbMigrationsSqlGenerator>();
DbContext:
entity.HasIndex(log => new { log.Id }).Include<Log>(log => new { log.Type, log.Source, log.Created, log.Message })
Этот код работает нормально сSQL Server, но не работает с Postgresql.Не удается добавить команду включения в запрос CreateIndex.Спасибо за вашу поддержку.