行插入顺序实体框架 [英] Row insertion order entity framework

查看:22
本文介绍了行插入顺序实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用事务在多个表中插入多行.对于这些行,我想按顺序添加这些行.调用 SaveChanges 后,所有行都被乱序插入.

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.

推荐答案

在实体框架中插入/更新和删除的顺序取决于实体框架中的许多内容.

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?

希望能帮到你

亚历克斯

项目经理实体框架团队

这篇关于行插入顺序实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆