public static class RemoveForeignKeyExetension { public static ModelBuilder RemoveForeignKeys(this ModelBuilder modelBuilder) { var entityTypes = modelBuilder.Model.GetEntityTypes().ToList(); for (int i = 0; i < entityTypes.Count(); i++) { var entityType = entityTypes[i]; var references = entityType.GetDeclaredReferencingForeignKeys().ToList(); using (((Model)entityType.Model).Builder.Metadata.ConventionDispatcher.DelayConventions()) { foreach (var reference in references) { reference.DeclaringEntityType.RemoveForeignKey(reference); } } } return modelBuilder; }
忽略外键约束(SQLite)
上述是针对SQL Server所做的测试,理论上MySQL同理,但对于SQLite数据库,EF Core 3.x提供了全局方案:通过数据连接字符串配置【Foreign Keys = False】全局抑制建立外键约束。
optionsBuilder.UseSqlite("Database=sqlite.db;Foreign Keys=False");
官方团队好像并未提供针对SQL Server或MySQL忽略而不建立外键约束而可以加载导航属性的办法,只能采取笨拙或者如上所述写个程序去删除外键约束或者通过注解方式实现。
EFCore 迁移命令移除外键
https://www.cnblogs.com/lludcmmcdull/p/13502567.html
https://blog.51cto.com/u_15065850/3444526