L
L
lucky42022-04-18 17:45:25
C++ / C#
lucky4, 2022-04-18 17:45:25

How to save records sorted in the database?

Hey! Me interests, how it is possible to thrust the sorted list in the table DB?
I debugged the code - into the saveThis variable => records are sorted by field, but after storing in the database - everything is chaotic

var saveThis = request.SomeField.Select(r => new Table2Db
                        {
...
                        }).OrderBy(x => x.FieldIntNumber).ToList();

                        ctx.Table2Db.AddRange(errorDbs);

//manipulation with another Table1
....
ctx.SaveChanges()


***The saveThis variable works with table2, followed by assignments of certain parameters for table1. They are in the same context.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2022-04-18
@lucky4

Most DBMSs do not guarantee the order in which records will appear when querying without sorting.
So if you need some specific order - use ORDER BY.
If you have some kind of complex sorting there, add a serial number when inserting and sort by it.

F
forced, 2022-04-18
@forced

Furthermore. It is almost forbidden to use the order of rows in the database. That is, by numbering. Access is by key or predicate. If you need to store the sorted list - in the cache.

O
oleg_ods, 2022-04-19
@oleg_ods

If you often need to pull out entities sorted by a particular field or set of fields from the database, then perhaps to improve performance, you should think about adding an index to this field/set of fields.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question