EF Core使用Code First迁移到数据库的时候如果设置了导航属性,生成数据库的时候就会建立外键关联,建立外键虽然能保证数据一致性,但是在整成维护的数据的时候简直就是噩梦了。 百度到这篇文章:https://www.cnblogs.com/lludcmmcdull/p/13502567.html 操作就是创建一个类继承MigrationsModelDiffer,重写它的GetDifferences ,去掉所有添加外键和删除外键的操作
/// <summary>
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<挂起>")]
public class MigrationsModelDifferWithoutForeignKey : MigrationsModelDiffer
{
public MigrationsModelDifferWithoutForeignKey
([NotNull] IRelationalTypeMappingSource typeMappingSource,
[NotNull] IMigrationsAnnotationProvider migrationsAnnotations,
[NotNull] IChangeDetector changeDetector,
[NotNull] IUpdateAdapterFactory updateAdapterFactory,
[NotNull] CommandBatchPreparerDependencies commandBatchPreparerDependencies)
: base(typeMappingSource, migrationsAnnotations, changeDetector, updateAdapterFactory, commandBatchPreparerDependencies)
{
}
public override IReadOnlyList<MigrationOperation> GetDifferences(IRelationalModel source, IRelationalModel target)
{
System.Console.WriteLine("debuger");
var operations = base.GetDifferences(source, target)
.Where(op => !(op is AddForeignKeyOperation))
.Where(op => !(op is DropForeignKeyOperation))
.ToList();
foreach (var operation in operations.OfType<CreateTableOperation>())
operation.ForeignKeys?.Clear();
return operations;
}
}
在startup里面替换掉默认的实现方法,这里说明一下我用的Furion框架,因为Furion框架默认的配置是在DefaultDbContext上打属性标签的。产生了一个问题,你打了属性标签,在调用services.AddDatabaseAccessor指定了option的参数,他不会合并配置。所以我取消了DbContext上的属性标签,在startup上进行配置。如果不用Fursion框架应该操作也是一样的,只是方法就不是 AddDatabaseAccessor了。
还有一个需要小注意的Fursion的 AddDbPool ,第三个参数是连接字符串,不能写key值。
public class Startup : AppStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDatabaseAccessor(options =>
{
options.AddDbPool<DefaultDbContext>(DbProvider.Sqlite,opt=> {
opt.ReplaceService<IMigrationsModelDiffer, MigrationsModelDifferWithoutForeignKey>();
}, App.Configuration["ConnectionStrings:WarehouseManage"]);
}, "WarehouseManage.Database.Migrations");
}
}
浙公网安备 33010602011771号