Insertion order of multiple records in Entity Framework

家住魔仙堡 提交于 2019-11-28 12:03:55
Ladislav Mrnka

What I'd like to know is how I can get these inserts to be ordered.

You cannot. Order of database commands is EF's internal behavior. If you want to control the order of commands don't use tools which abstract you from low level database interactions - use SQL directly.

Edit based on comment:

Yes it is low level interaction because you are putting expectations on the order of SQL commands when working with abstraction you don't have under your control. At high level you are getting something different because you are using expectations which don't work with that abstraction. If you want to have control over order of SQL commands you must either force EF by saving items one by one (=> multiple SaveChanges and TransactionScope) or write SQL yourselves. Otherwise use separate column for ordering.

Btw. EF doesn't save the entity as you see it. It has its own change tracker holding references to all your attached instances. References are held in multiple Dictionary instances and dictionary doesn't preserve insertion order. If these collections are used for generating SQL commands (and I guess they are) no order can be guaranteed.

Tables in the database are sets. That means that the order is not guaranteed. I assume in your example that you want the results ordered by "Number". If that is what you want, what are you going to do if that number changes and it doesn't reflect the order in the database anymore?

If you really want to have the rows inserted in a specific order, multiple SaveChanges are your best bet.

The reason nobody wants to call SaveChanges multiple times is because this feels exactly how it is: a dirty hack.

Since a primary key is a technical concept, it shouldn't make any functional sense to order your results on this key anyway. You can order the results by a specific field and use a database index for this. You probably won't see the difference in speed.

Making the ordering explicit has other benefits as well: it is easier to understand for people who have to maintain it. Otherwise that person has to know that ordering on primary key is important and gives the correct results, because in an other (completely) unrelated section of your application, it accidentally is the same order as the number field.

multiple Add() before a save or AddRange() before a save does not preserve order. Also when you are reading the collection it is not guaranteed to return the results in the same order they were originally added. You need to add some property to your entities and when you query use OrderBy() to ensure they come back in the order you want.

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