I'm quite new to C# MVC so what i'm asking might be bad practice, but is there a way (or should I attempt), to reorder the Ids of the objects in a collection so that the first element always remains with and Id of 1. If it gets deleted and replaced by the second element, this element should then get a new Id of 1.
I'm using Ids to order the displayed elements on a page, and I guess I could manage to create a new property that would serve this purpose, but I'm wondering if reordering the actual Ids would be a good/bad idea.
I'm using Code First, and I let entity manage the Ids automatically for now.
Any advice on the matter will be very welcome!
Thanks in advance!
答案 0 :(得分:2)
Yes, you're right in your assumption. Firstly, you should not be using the IDs for sorting. The purpose of the IDs is to identify the records and you should not use them for other purposes. More importantly, it is a very bad idea to change the IDs except in very special cases. When you modify an ID, all related records with foreign IDs referencing the modified IDs need to be changed too.
You are also right that the best way is to add another column called something like "SortingOrder" and use that for your ordering. I do it all the time, and most my tables that need ordering that is decided by the admin have a column called "SortingOrder" (or "sorting_order" in SQL).