无论如何,当您在Entity Framework Core中调用Add-Migration
时,是否可以访问用于创建数据库迁移的方法?
如果这有所不同,则它在.NET Core 2.2项目中。
答案 0 :(得分:1)
要访问Migration
,可以实现MigrationsAssembly
。
实施ColumnOrderMigrationAssembly
public class ColumnOrderMigrationAssembly : MigrationsAssembly
{
private readonly DbContext _context;
public ColumnOrderMigrationAssembly(ICurrentDbContext currentContext,
IDbContextOptions options, IMigrationsIdGenerator idGenerator,
IDiagnosticsLogger<DbLoggerCategory.Migrations> logger)
: base(currentContext, options, idGenerator, logger)
{
_context = currentContext.Context;
}
public override Migration CreateMigration(TypeInfo migrationClass,
string activeProvider)
{
var migration = base.CreateMigration(migrationClass, activeProvider);
var productTableMigration = migration.UpOperations.FirstOrDefault(m => m.GetType() == typeof(CreateTableOperation)
&& ((CreateTableOperation)m).Name == "Products") as CreateTableOperation;
if (productTableMigration != null)
{
var columns =new List<AddColumnOperation>(productTableMigration.Columns.OrderBy(o => o.Name));
productTableMigration.Columns.Clear();
productTableMigration.Columns.AddRange(columns);
}
return migration;
}
}
注册ColumnOrderMigrationAssembly
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"))
.ReplaceService<IMigrationsAssembly, ColumnOrderMigrationAssembly>());
启用migrate
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
//your rest code
using (var db = serviceProvider.CreateScope().ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
db.Database.Migrate();
}
}
根据自己的需要更改CreateMigration
中的逻辑。
答案 1 :(得分:0)
在运行Add-Migration的项目下,有一个名为Migration的文件夹,在其中添加了Migration类。重新运行迁移时,您可以更改列的顺序。