Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

transactions - Row insertion order entity framework

I'm using a transaction to insert multiple rows in multiple tables. For these rows I would like to add these rows in order. Upon calling SaveChanges all the rows are inserted out of order.

When not using a transaction and saving changes after each insertion does keep order, but I really need a transaction for all entries.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The order inserts/updates and deletes are made in the Entity Framework is dependent upon many things in the Entity Framework.

For example if you insert a new Product in a new Category we have to add the Category before the Product.

This means that if you have a large set of changes there are local ordering constraints that we must satisfy first, and indeed this is what we do.

The order that you do things on the context can be in conflict with these rules. For example if you do this:

ctx.AddToProducts(
   new Product{
      Name = "Bovril",
      Category = new Category {Name = "Food"}
   }
);

the effect is that the Product is added (to the context) first and then when we walk the graph we add the Category too.

i.e. the insert order into the context is:

Product
Category

but because of referential integrity constraints we must re-order like this before attempting to insert into the database:

Category
Product

So this kind of local re-ordering is kind of non-negotiable.

However if there are no local dependencies like this, you could in theory preserve ordering. Unfortunately we don't currently track 'when' something was added to the context, and for efficiency reason we don't track entities in order preserving structures like lists. As a result we can't currently preserve the order of unrelated inserts.

However we were debating this just recently, so I am keen to see just how vital this is to you?

Hope this helps

Alex

Program Manager Entity Framework Team


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...