ZZZ Code AI
Report Issues
Suggest Features
Login
Dapper Tools
Chat
Code Explain
Seed Data Generator
Sql Generator
Stored Procedure Generator
Entity to Table Converter
Table to Entity Converter
Sql Injection Detector
More Tools
How to insert data including the identity value in Dapper?
<p>To insert data, including the identity value, you have 2 choices:</p> <ol> <li>Use the <code>Execute</code> method and turn on the <a href="https://learn.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql?view=sql-server-ver16">identity insert</a></li> <li>Use <a href="https://dapper-plus.net/">Dapper Plus</a> with the <code>InsertKeepIdentity</code> option</li> </ol> <p><strong>Solution 1</strong></p> <pre><code class="language-csharp">using (var connection = new SqlConnection(connectionString)) { var sql = @" SET IDENTITY_INSERT Customers ON INSERT INTO Customers (CustomerID, Name, Email) VALUES (@CustomerID, @Name, @Email) "; var customer = new Customer() { CustomerID = 13, Name = "Learn Dapper", Email = "learndapper@example.com" }; connection.Execute(sql, customer); Console.WriteLine(customer.CustomerID); } </code></pre> <p><strong>Solution 2</strong></p> <pre><code class="language-csharp">// global context mapping: https://dapper-plus.net/getting-started-mapping#global-context-mapping DapperPlusManager.Entity<Customer>().Identity(x => x.CustomerID); using (var connection = new SqlConnection(connectionString)) { var customer = new Customer() { CustomerID = 13, Name = "Learn Dapper", Email = "learndapper@example.com" }; connection.UseBulkOptions(x => x.InsertKeepIdentity = true).BulkInsert(customer); Console.WriteLine(customer.CustomerID); } </code></pre>
Sponsored by
Dapper Plus
This field is required
A text with a minimum of 10 characters is required
Send
Legal & Licensing
Answer generated by AI may produce inaccurate information about code, people, facts, and more.
Advertising Break!
5
seconds left
Did you know...
That you can now sponsor this project on
GitHub
?