本文介绍了哪种逻辑确定Entity Framework 6的插入顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个DBContext,并且正在执行以下操作:

So, I have a DBContext, and I am doing the following operations:

dbContext.SomeTables1.Add(object1)
dbContext.SomeTables2.AddRange(objectArray2)
dbContext.SomeTables3.AddRange(objectArray3)
dbContext.SaveChanges();

EF不会按此顺序插入db记录,而是以随机顺序插入它们.要以相同的顺序插入它们,每次添加后都必须执行dbContext.SaveChanges().这不是一个有效的解决方案,就我而言,完成所有插入操作需要10秒钟,而一次保存的随机订单大约需要3秒钟.

The EF doesn't insert the db records in this order, it inserts them in a random order. To insert them in the same order, I have to do a dbContext.SaveChanges() after each addition. This is not an efficient solution and in my case, it is taking 10 seconds to do all my inserts, while the random order with one save takes around 3 seconds.

我需要正确的顺序来解决死锁问题.

N.B. I need the right order to solve a deadlock issue.

我的问题是:

推荐答案

  • 您无法在EF6或EF Core(最初称为EF7)中指定保存顺序.
  • 该问题在EF Core(最初称为EF7)中没有解决,因为这不是问题.
  • 如果前任相同,则顺序将相同(这种情况很少发生)
  • 当您调用SaveChanges时,所有实体都按照"ProduceDynamicCommands"方法从内部顺序进行排序,然后再次通过"TryTopologicSort"方法进行排序,该方法循环以添加命令而没有前任(如果您添加A和B且A依赖于在B上,那么B将在A之前插入)

    When you call SaveChanges, all entities are ordered from an internal order in the method "ProduceDynamicCommands" then sorted again by the method "TryTopologicalSort" which loops to add command with no predecessor left (if you add A and B and A depend on B, then B will be inserted before A)

    您需要通过批量添加进行插入.

    You are left to insert by batch addition.

    由于执行插入需要3秒钟的时间,因此我假设您有数千个实体,执行批量插入可能会提高您的性能,从而将10秒减少到更少,然后可能是最初的3秒!

    Since it takes you 3 seconds to perform your insert, I will assume you have thousands of entities and performing bulk insert may improve your performance to reduce the 10 seconds to less, and then maybe the initial 3 seconds!

    这里有2个我可以推荐的库:

    Here are 2 libraries I can recommend:

    • https://efbulkinsert.codeplex.com/
      • 免费,但不适用于所有类型的关联和继承
      • https://efbulkinsert.codeplex.com/
        • FREE but doesn’t work with all kind of associations and inheritances
        • 已付费,但支持所有功能
        • PAID but support everything

        免责声明:我是Entity Framework Extensions项目的所有者.

        Disclaimer: I'm the owner of the Entity Framework Extensions project.

        这篇关于哪种逻辑确定Entity Framework 6的插入顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 21:02