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 and return the id in Dapper?
<p>To insert data and return the id, you have 2 choices:</p> <ol> <li>Use the <code>Execute</code> method and select the identity inserted with <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql">SCOPE_IDENTITY()</a></li> <li>Use <a href="https://dapper-plus.net/">Dapper Plus</a> with the property mapped as identity or output</li> </ol> <p><strong>Solution 1</strong></p> <pre><code class="language-csharp">using (var connection = new SqlConnection(connectionString)) { var sql = @" INSERT INTO Customers (Name, Email) VALUES (@Name, @Email) SELECT SCOPE_IDENTITY() "; var customer = new Customer() { Name = "Learn Dapper", Email = "learndapper@example.com" }; var customerID = connection.Execute(sql, customer); customer.CustomerID = customerID; 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() { Name = "Learn Dapper", Email = "learndapper@example.com" }; connection.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
?