<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kedar Kalkote on Medium]]></title>
        <description><![CDATA[Stories by Kedar Kalkote on Medium]]></description>
        <link>https://medium.com/@kalkotekedar?source=rss-286899605af9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SjOrh0dr_A1oYLXRK9Fhtw.jpeg</url>
            <title>Stories by Kedar Kalkote on Medium</title>
            <link>https://medium.com/@kalkotekedar?source=rss-286899605af9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:48:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalkotekedar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Efficient Bulk Insert into MySQL using Dapper in .Net Core]]></title>
            <link>https://kalkotekedar.medium.com/efficient-bulk-insert-into-mysql-using-dapper-in-net-core-501f05a235ed?source=rss-286899605af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/501f05a235ed</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[bulk-insert]]></category>
            <category><![CDATA[optimized]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[dapper]]></category>
            <dc:creator><![CDATA[Kedar Kalkote]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 18:21:40 GMT</pubDate>
            <atom:updated>2024-10-24T18:21:40.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Bulk Insert into MySQL using Dapper in .Net Core</h3><p>The problem statement requires executing bulk insertions into a MySQL database where foreign key constraints interlink tables. It is crucial to ensure that <strong>referential integrity</strong> is maintained throughout the insertion process. This means that any foreign key relationships between tables must be respected and enforced during the bulk data insertion, ensuring that the data remains consistent and valid across the related tables.</p><p><strong>Scenario: Bulk Insertion in MySQL with Referential Integrity</strong></p><p>Many of us might have faced this issue of bulk insertion in the MySQL database. I have tried a workaround to solve this problem using <strong>Dapper</strong> and <strong>.Net Core 8.0</strong>. This might help you the same.</p><p><a href="https://en.wikipedia.org/wiki/Dapper_ORM"><strong>Dapper</strong></a> is a high-performance micro ORM (Object-Relational Mapper) library for .NET. It simplifies the process of interacting with databases by mapping database records to .NET objects with minimal overhead, and it still provides developers full control over SQL queries. Dapper is focused on performance, making it an ideal choice for scenarios where speed and fine-tuned SQL are crucial.</p><p><strong>Key Features of Dapper</strong>:</p><ul><li><strong>Fast execution</strong>: Minimal overhead with near raw ADO.NET performance.</li><li><strong>Simple object mapping</strong>: Maps SQL result sets to strongly typed objects.</li><li><strong>Support for multiple databases</strong>: Works with SQL Server, MySQL, PostgreSQL, and others.</li><li><strong>Extensibility</strong>: Easily extendable to handle more complex use cases.</li><li><strong>Asynchronous support</strong>: Leverages async/await patterns for non-blocking database access.</li></ul><p>Now come to the problem that we are trying to solve. We have an employee database the table structure you can see in the image below. We have thousands of records that we want to insert in these tables by maintaining their referential key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*cLB8FuZMiUQf5_Kzkah-tA.png" /><figcaption>Employee Database</figcaption></figure><p>In the above database structure, you can check an <em>emp_id</em> has a reference for the <em>Address</em> and <em>EmployeeAddress</em> Table. A temp_id in the table <em>EmployeeMaster</em> and <em>AddressMaster</em> is taken as this will help us map the primary key with the temporary key of these two tables.</p><p>We are using a stored procedure to insert the data into the respective table. We are using <strong>Table Value Parameter(TVP)</strong> to pass the data to a stored procedure. So let’s create the table types first <em>EmployeeMasterType</em>, <em>AddressMasterType</em>, and <em>EmployeeAddressMasterType</em>.</p><pre>--- Table type for EmployeeType<br>CREATE TYPE [dbo].[EmployeeType] AS TABLE<br>(<br>    Name NVARCHAR(100),<br>    Email NVARCHAR(100),<br>    TempId INT<br>);<br><br>--- Table type for SalaryType<br>CREATE TYPE [dbo].[SalaryType] AS TABLE<br>(<br>    TempEmpId INT,<br>    Salary INT,<br>    Status INT<br>);<br><br>--- Table type for AddressType<br>CREATE TYPE [dbo].[AddressType] AS TABLE<br>(<br>    TempEmpId INT,<br>    LineOne NVARCHAR(100),<br>    LineTwo NVARCHAR(100),<br>    Country NVARCHAR(100),<br>    State NVARCHAR(100),<br>    City NVARCHAR(100),<br>    PinCode NVARCHAR(100),    <br>);</pre><p>Now let’s create a stored procedure which will take these table types as a parameter.</p><pre>CREATE PROCEDURE [dbo].[BulkInsertEmployees]<br>    @PEmployee [dbo].[EmployeeType] READONLY,<br>    @PSalary [dbo].[SalaryType] READONLY,<br>    @PAddresses [dbo].[AddressType] READONLY<br>AS<br>BEGIN<br>    SET NOCOUNT ON;    <br><br>    --- Step 1 Insert data into Employee <br>    INSERT INTO Employee (Name, Email, TempId)<br>    SELECT Name, Email, TempId FROM @PEmployee;<br><br>    --- Step 2: Insert data into Salary<br>    INSERT INTO Salary (EmpId, Salary, Status)<br>    SELECT e.Id, s.salary, s.Status<br>    FROM @PSalary s<br>    LEFT JOIN Employee e ON e.TempId = s.TempEmpId;<br><br>    --- Step 3: Insert data into EmployeeAddresses<br>    INSERT INTO Address (EmpId, LineOne, LineTwo, Country, State, City, PinCode)<br>    SELECT e.Id, a.LineOne, a.LineTwo, a.Country, a.State, a.City, a.PinCode<br>    FROM @PAddresses a<br>    LEFT JOIN Employee e ON e.TempId = a.TempEmpId;<br><br>    --- Clean up tempIds table<br>    UPDATE TABLE Employee<br>    SET TempId = NULL WHERE TempId IS NOT NULL;<br>END;  </pre><p>Now we move on to the .Net part will define the schema of the data tables and insert the data into them. Once the data is inserted into this table we just have to pass the data to the stored procedure as a parameter.</p><pre>var employeeTable = new DataTable();<br>employeeTable.Columns.Add(&quot;Name&quot;, typeof(string));<br>employeeTable.Columns.Add(&quot;Email&quot;, typeof(string));<br>employeeTable.Columns.Add(&quot;TempId&quot;, typeof(int));<br><br>DataTable salaryTable = new DataTable();<br>salaryTable.Columns.Add(&quot;TempEmpId&quot;, typeof(int));<br>salaryTable.Columns.Add(&quot;Salary&quot;, typeof(int));<br>salaryTable.Columns.Add(&quot;Status&quot;, typeof(int));<br><br>var addressTable = new DataTable();<br>addressTable.Columns.Add(&quot;TempEmpId&quot;, typeof(int));<br>addressTable.Columns.Add(&quot;LineOne&quot;, typeof(string));<br>addressTable.Columns.Add(&quot;LineTwo&quot;, typeof(string));<br>addressTable.Columns.Add(&quot;Country&quot;, typeof(string));<br>addressTable.Columns.Add(&quot;State&quot;, typeof(string));<br>addressTable.Columns.Add(&quot;City&quot;, typeof(string));<br>addressTable.Columns.Add(&quot;PinCode&quot;, typeof(string));<br><br>int TempId = 0;<br><br>foreach (var employee in employees)<br>{<br>    TempId++;<br>    employeeTable.Rows.Add(TempId, employee.Name, employee.Email);<br>    <br>    var salary = employee.salary;<br>    salaryTable.Rows.Add(TempId, salary.Salary, salary.Status)<br><br>    var address = employee.address.<br>    addressTable.Rows.Add(TempId, address.LineOne, address.LineTwo, address.Country, address.State, address.City, address.PinCode);<br>}</pre><pre>var parameters = new DynamicParameters();<br>parameters.Add(&quot;@PEmployee&quot;, employeeTable.AsTableValuedParameter(&quot;EmployeeType&quot;));<br>parameters.Add(&quot;@PSalary&quot;, salaryTable.AsTableValuedParameter(&quot;SalaryType&quot;));<br>parameters.Add(&quot;@PAddresses&quot;, addressTable.AsTableValuedParameter(&quot;AddressesType&quot;));<br><br>connection.Execute(&quot;BulkInsertEmployees&quot;, parameters, commandType: CommandType.StoredProcedure, CommandTimOut: 300);</pre><p>Using this way I can bulk insert the data efficiently into the database. Logging is important to overcome the issue and saves time a lot.</p><p>I am not sure if this is an optimized way if any other is available please share it with me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lI6I_yl3Aqgch8nzc5pQTg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501f05a235ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>