EF CodeFirst create non-clustered primary key index

佐手、 提交于 2019-11-30 15:00:51

问题


I'm using EF 4.1 CodeFirst to create my DB. It seems that EF is creating all primary keys with clustered index, which is not optimal for us in one case(possibly more cases). Is there a way to tell EF to generate this table with primary key as a non-clustered index ?

Of course we could do it manually using custom script after database is already created, but we have a lot of foreign keys pointing to this table, it would be quite a non-optimal solution if there is a better, more straight forward way to do the same already during DB creation. Any help appreciated


回答1:


No there is no way to control SQL code first generates - it is code first and its current philosophy (the bad one actually) is: you know nothing about the database and you don't bother.

The only way to change this behavior is to write custom database initializer, use custom database queries to search for created index, remove that index and create a new one. Some references:

  • How to stop EF4.1 Code-First to create Culstered index for the entity PK
  • Custom initializer with adding an index
  • Example of more advanced initializer

The initilizer will make your solution dependent on the concrete database server product.




回答2:


Yes there is a way you can specify not to create Clustered Indexes. If you use code migrations, a *.cs file is generated in order to populate your DataBase. In this file you can specify apart from the Primary key for each table, if it needs to be created with clustered indexes.

  .PrimaryKey(t => t.MID, null, true)


来源:https://stackoverflow.com/questions/6813462/ef-codefirst-create-non-clustered-primary-key-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!