我首先使用了数据库,并遵循这个SO 问题 ,改变了一个类并做了,
add-migration -context myContext AddNewClassProperty update-database -context myContext它运行良好。
但是如果我想从数据库中删除一列数据呢? 在后来的发展中,我确定应该有一个新课程,并从另一个课程中删除属性。
当我构建我的项目时,我的dbContext类中的错误表现出来,因为我已经删除了这些属性,因此modelBuilder.Entity方法找不到类成员。 这就说得通了。
那时我不知道的是我如何进行移民。 我试图添加一个新的迁移,但我得到同样的失败。
我如何从PMC迁移? 这是真的,我首先与数据库和代码来回。 也许那是现在让我感到悲伤。
I used database first and followed this SO question, changed a class and did,
add-migration -context myContext AddNewClassProperty update-database -context myContextand it worked fine.
But what if I want to remove a column(s) from the database? Later in development, I determined there should be a new class and a removal of properties from another class.
When I built my Project the errors in my dbContext class manifested because I had removed the properties and thus the modelBuilder.Entity method could not find class members. That makes sense.
What I don't know then is how I make the migration. I tried to add a new migration, but I get same failure.
How do I do the migration from the PMC? It is true I am going back and forth with database and code first. Perhaps that is causing me woe now.
最满意答案
EF Core有一种处理迁移和监视数据库状态的新方法。 这有正面和负面的后果。 从积极的方面来看,EF Core不再需要完全控制数据库。 对于这个问题,您可以混合并匹配代码优先的表和数据库优先的表,或者EF甚至不知道或关心的表。
但是,这样做的结果是,除非EF实际负责创建表,否则无法操作它。 EF用于监视状态的类不会有关于这些表的任何信息,因此无法操作它们。
无论你走到哪里,我都会说选择一条路,然后继续前进。 如果你想先做代码,那么先做代码。 让EF管理状态并生成迁移,并且不要直接触摸数据库。 如果您想处理数据库模式更改,那么请执行此操作,并且不要混淆EF迁移。 尝试混合搭配会让你的POCO和数据库不同步,并导致像你遇到的问题。
EF Core has a new way of handling migrations and monitoring database state. This has both positive and negative consequences. On the positive side, EF Core no longer requires full control over the database. You can mix and match tables that are code first and tables that are database first or that EF doesn't even know or care about, for that matter.
However, the result of this, is that unless EF was actually responsible for creating the table, it cannot manipulate it. The class that EF uses to monitor state won't have any information about these tables, and therefore cannot manipulate them.
Whichever way you go, I would say pick just one way and go forward with that. If you want to do code first, then do code first. Let EF manage the state and generate migrations, and don't ever touch the database directly. If you want to handle database schema changes, then do so, and don't mess with EF migrations. Trying to mix and match is going to get your POCOs and database all out of sync and lead to problems like what you're experiencing.
更多推荐
发布评论