简体   繁体   English

在 EF Core 5 中检测模型和数据库是否不同步

[英]Detect whether model and database out of sync in EF Core 5

I'm using the "Create and Drop" APIs since my model changes often.我正在使用“创建和删除” API,因为我的模型经常更改。

After a model change, I call dotnet ef database drop , and on next run the system calls context.Database.EnsureCreated() to recreate the database.模型更改后,我调用dotnet ef database drop ,并在下次运行时系统调用context.Database.EnsureCreated()来重新创建数据库。 I could precede that with context.Database.EnsureDeleted() but I don't want to drop/recreate the database every time (it slows down the development "inner loop", and it'll hammer my drive).我可以先使用context.Database.EnsureDeleted()但我不想每次都删除/重新创建数据库(它会减慢开发“内部循环”的速度,并且会影响我的驱动器)。

There used to be an easy way (in old EF) to programmatically detect if the database and model are out of sync .曾经有一种简单的方法(在旧的 EF 中)以编程方式检测数据库和模型是否不同步 There isn't such a built-in feature in EF Core. EF Core 中没有这样的内置功能。 There are some ways ( eg , eg ) but they are a few years old, unreliable (depend on internal features) and for older versions.有一些方法(例如eg ),但它们已经有几年的历史了,不可靠(取决于内部功能)并且适用于较旧的版本。

Is there a stable way - without using internal assembly features - to do this in v5 ?有没有一种稳定的方法——不使用内部装配特征——在v5 中做到这一点?

You can get EF Core to serialise your schema ( context.Model ) into a string using .Model.DebugView.LongView .您可以让 EF Core 使用.Model.DebugView.LongView将您的架构( context.Model )序列化为字符串。

Then I would calculate a hash value from that string, and compare that hash to a value stored in a table.然后我会从该字符串计算一个哈希值,并将该哈希值与存储在表中的值进行比较。

Since EF Core doesn't expose a method to run a raw select query, particularly if you can't depend on the schema being up-to-date.由于 EF Core 不公开运行原始选择查询的方法,特别是当您不能依赖最新的架构时。 You would either need to use SqlConnection directly to query the table.您需要直接使用SqlConnection来查询表。

Or construct your comparison as an insert / update statement so you can decide what to do based on number of rows affected.或者将您的比较构建为insert / update语句,以便您可以根据受影响的行数决定要执行的操作。 Since you're going to destroy the database immediately, side effects of that sql can be ignored.由于您将立即销毁数据库,因此可以忽略该 sql 的副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM