简体   繁体   中英

Entity Framework Code First Usage

I have a simple question. We are using a database in MVC application to save our contacts. But when the tables updated, row's id was incrementing. Some question has entered in my mind which is about integer's limit. In our table Id variables are integer. It can crash by it's limit. So i wrote it into my project,

 context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('Contacts', RESEED, 0)");

Can i use it in Code First Entity Framework? Is it legit? Thanks...

Can i use it in Code First Entity Framework? Is it legit? Thanks...

as what @ jpgrassi said this might casues for you a serious problems.

What you can do to solve the problem?

Solution 1) You can Reorganize and Rebuild Indexes as following:*

context.Database.ExecuteSqlCommand("ALTER INDEX ALL ON Contacts REORGANIZE;"); context.Database.ExecuteSqlCommand("ALTER INDEX ALL ON Contacts REBUILD;");

  • You have to take care that your bussines logic is not rely on the primery key eg you do not have something like that in your code if(Contact.Id == 1)...

  • Make an extra task for this job in your applicaiton eg once pro week and do not execute this command everytime by application starting or DbContext creating!

More info:

https://msdn.microsoft.com/en-us/library/ms189858.aspx https://www.brentozar.com/archive/2013/09/index-maintenance-sql-server-rebuild-reorganize/

Solution 2) Use a long in the primary key instaed of int

public long Id {get;set;}

Notes:

If an index is between 10% and 30% fragmented, I will REORGANIZE the index and UPDATE the statistics. If an index is over 30% fragmented, I will REBUILD the index - with no UPDATE STATISTICS, as this is taken care of by the REBUILD. Remember though that a rebuild only updates the statistics object directly associated with the index. Other column statistics will need to be maintained separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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