更改为现有数据库上的共享主键?
我有一个看起来像这样的现有表结构:
AnimalTable
-------------
|Id |
|Color |
|Weight |
|AnimalType |
-------------
CatTable
----------------
|Id |
|MeowSound |
|AnimalTableId |
----------------
DogTable
----------------
|Id |
|BarkSound |
|AnimalTableId |
----------------
AnimalType
是“Cat”或“Dog”。基本上,它是一个“每种类型表”结构加上 AnimalTable 中附加的“AnimalType”鉴别器。这显然是一个人为的示例,但我的项目有一个类似的设置,并且已经使用了很长一段时间。我们开始转换一些内容以使用 EF Code First 方法,我想使用相同的架构,这样我就有一个抽象的 Animal 类和具体的 Cat 类code> 和 Dog
类。
从头开始设置似乎非常简单,但我不确定更改现有表上的主键以使其就像我一直在使用 EF 一样的最佳方法是什么。有人这样做过并且可以提供一些提示/方向吗?提前致谢。
I have an existing table structure that looks something like this:
AnimalTable
-------------
|Id |
|Color |
|Weight |
|AnimalType |
-------------
CatTable
----------------
|Id |
|MeowSound |
|AnimalTableId |
----------------
DogTable
----------------
|Id |
|BarkSound |
|AnimalTableId |
----------------
AnimalType
is either "Cat" or "Dog". Basically, it's a "Table Per Type" structure plus the additional "AnimalType" discriminator in the AnimalTable. This is obviously a contrived example, but my project has a similar setup that has been in use for a good amount of time. We're starting to convert some stuff over to use the EF Code First approach, and I'd like to use this same schema so I have an abstract Animal
class, and concrete Cat
and Dog
classes.
Setting this up from scratch seems pretty straightforward, but I'm not sure what the best way to go about changing the primary keys on my existing tables to make it as if I had been using EF all along. Has anyone done this and can provide some tips/direction? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终编写了一个存储过程,实质上删除了
CatTable
和DogTable
中的Id
列,并将AnimalTableId
重命名为Id
,并将其作为主键。听起来很简单,但困难的部分是编写一些内容来一般性地修复已经指向CatTable.Id
和DogTable.Id
的所有外键。I ended up writing a stored procedure that essentially dropped the
Id
column in theCatTable
andDogTable
, renamedAnimalTableId
toId
, and made that the primary key. Sounds easy enough, but the hard part was writing something that would generically fix all the foreign keys already pointed atCatTable.Id
andDogTable.Id
.升级脚本。
将来您将因架构的其他更改而面临相同的决定。在您的开发中,您可以重构类并让 EF 为您生成数据库。当您转向生产时,您还需要生成一个升级生产的脚本。
要更改主键,请使用:
Upgrade scripts.
You'll face the same decision in the future with other changes of the schema. In your development you can refactor the classes and let EF generate the database for you. When you move to production you also need to produce a script that upgrades production.
To change the primary keys use: