Parallel ForEach with SQL inserts c#

試著忘記壹切 提交于 2019-12-20 03:52:12

问题


I have an object like the below but with a huge amount of data, we observed that it takes a long to be inserted into our SQL database as we were using normal foreach, the main idea is to insert each Department and get the generated identity number, then insert the nested employees assigned with that department ID.

<Sample>
    <Departments>
        <Department>
            <Name>HR</Name>
            <Employees>
                <Employee>
                    <Name>Marco</Name>
                </Employee>
                <Employee>
                    <Name>John</Name>
                </Employee>
                <Employee>
                    <Name>Sarah</Name>
                </Employee>
            </Employees>
        </Department>
        <Department>
            <Name>IT</Name>
            <Employees>
                <Employee>
                    <Name>Ali</Name>
                </Employee>
                <Employee>
                    <Name>Roberto</Name>
                </Employee>
                <Employee>
                    <Name>Franco</Name>
                </Employee>
            </Employees>
        </Department>
    </Departments>
</Sample>

We tried to use Parallel.ForEach to enhance the performance, and it does, but we got another issue with @@IDENTITY because there is an overlap between the running tasks in Parallel.ForEach as we found an employee is assigned to another department.

The need ... I need to speed the process up either I use Parallel.ForEach or foreach ... any ideas?

BTW ... we are calling a stored procedures which contains normal INSERT INTO command using classing ADO.NET


回答1:


You could use guid as primary key into your table. It would help you to avoid problem with @@IDENTITY. At first you should generate new guid-identity, thank insert the generated value into a row



来源:https://stackoverflow.com/questions/50995648/parallel-foreach-with-sql-inserts-c-sharp

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