C# – Use SqlDbType.Structured for table parameters

To use a table-valued parameter (TVP) with SqlCommand (ADO.NET), pass in a DataTable as a SqlDbType.Structured parameter, like this: I’ll show a full example, starting with creating a TVP type and then inserting it as a SqlDbType.Structured parameter as shown above. 1 – Create the TVP type in SQL Server To be able to pass … Read more

C# – Select a single row with Dapper

When you want to select a single row with Dapper, the simplest option is to use QuerySingleOrDefault() with a SELECT + WHERE query (and pass in the parameters / model type like usual). Here’s an example: This SQL query returns a single row from the Movies table and Dapper maps it and returns a Movie … Read more

C# – Update records with Dapper

You can update records with Dapper by using Execute() with an UPDATE statement and passing in the parameters. Here’s an example: Dapper maps the properties from the param object to the query parameters (ex: it maps year to @year). You can pass in the parameters with an anonymous type (as shown above) or by passing … Read more

C# – Delete records with Dapper

You can delete records with Dapper by using Execute() with a DELETE statement and specifying the record ID as a parameter. Here’s an example: This deletes a single record from the Movies table. Delete multiple records When you’re deleting multiple records, you can efficiently execute a single DELETE statement with a WHERE clause including all … Read more

C# – Get column values by name instead of by number with SqlDataReader

When you execute a SQL query and read the results with SqlDataReader, you have two options for getting column values by name (instead of by ordinal number): I’ll show examples below. Read column by name with the indexer You can use the indexer to read columns by name (or by ordinal number). This returns an … Read more

C# – Use records as a shortcut for defining DTOs

You can declare a record with a single line of code: Note: This feature was added in .NET 5 / C# 9. Records are basically classes (reference types) that work very well as simple data containers (i.e. DTOs). Here’s an example of using a record: This outputs the following: As shown, when you declare a … Read more

C# – Get inserted identity value with Dapper

When you insert a record into a table with an identity column, the value for the identity column is automatically generated for you. The simplest way to get the inserted identity value is to put OUTPUT INSERTED.<identity column name> in the insert statement: To get the output value with Dapper, use ExecuteScalar<int>(): This inserts the … Read more

C# – Adding dynamic parameters with Dapper

The simplest way to add dynamic parameters when executing queries with Dapper is by passing in Dictionary<string, object>, like this: Read more about how to add items to a dictionary. You can also add dynamic parameter by using the DynamicParameters class. You can use whichever approach is simplest in the given scenario. In this article, … Read more

C# – Map query results to multiple objects with Dapper

When you’re querying joined tables, you can map each row to multiple objects by using the multi mapping feature in Dapper. To multi map, you have to provide Dapper with the following: In this article, I’ll show examples of multi mapping. Note: If you don’t specify the split column, it’ll use the default of “Id”. … Read more

C# – Using SQL transactions with Dapper

When you want to execute multiple SQL commands with Dapper in a transaction, using TransactionScope is the simplest option. Here’s an example of how to use it: When you call TransactionScope.Complete(), it commits the transaction. If you don’t call Complete(), it’ll rollback the transaction once it leaves the TransactionScope block. This keeps the code nice … Read more

C# – Table-valued parameters (TVP) with Dapper

Table-valued parameters (TVP) allow you to send multiple rows of data as a parameter into SQL queries. This is useful for SELECTs and INSERTs. In this article, I’ll show how to create a TVP in SQL Server and then use it in queries with Dapper. 1 – Create the TVP in SQL Server To be … Read more

System.Data.SqlClient is missing in a .NET Core project

When you create a new project in .NET, and you try to use a class from ADO.NET, such as SqlConnection or SqlDataReader, you’ll get missing reference errors. For example, your code might look something like this, and it’ll have red-squiggly lines under SqlConnection: In the past, you’d simply add a reference to System.Data.SqlClient, like this: … Read more

C# – The nameof() operator

The nameof() operator outputs the name of the class/method/property/type passed into it. Here’s an example: Note: nameof() was added in C# 6. nameof() eliminates duplication The DRY principle – Don’t Repeat Yourself – warns us against having duplication in the code. Whenever information or code is duplicated, it’s possible to change something in one spot … Read more

C# – How to unit test code that uses Dapper

Dapper makes your code difficult to unit test. The problem is that Dapper uses static extension methods, and static methods are difficult to mock out. One approach is to wrap the Dapper static methods in a class, extract out an interface for that wrapper class, and then dependency inject the wrapper interface. In the unit … Read more

C# – SQL Bulk Insert with SqlBulkCopy

When you need to insert multiple rows into the database, consider doing a Bulk Insert instead of inserting one row at a time. Bulk Insertions are up to 20x faster than executing SQL Insert repeatedly. The simplest way to do a SQL Bulk Insert is by using the built-in SqlBulkCopy (from System.Data.SqlClient) with a DataTable. … Read more

C# – How to handle nulls with SqlDataReader

SqlDataReader returns a DBNull object when a column is null. This isn’t the same as a C# null. You can check if the column is null by comparing it with DBNull.Value or by using SqlDataReader.IsDBNull(). Here’s an example showing these two ways of checking if a column is null: After checking if the column is … Read more

C# – Using SqlDataReader to process multiple result sets

In this article I’ll show how to use the SqlDataReader ADO.NET class in two scenarios involving multiple result sets: I have a StreamingService database that has Movies, Shows, and Episodes tables (linked to the shows). First I’ll show the model classes I’m mapping the data into. Then I’ll show the two scenarios where I’m using … Read more

C# – Conditionally catch exceptions with filtering

You can use exception filtering to conditionally catch exceptions, like this: Note: This feature was added in C# 6. Any SqlException that doesn’t meet the condition specified in the when clause will not be caught. Previously, without exception filtering, you’d have to handle that scenario in the catch block and rethrow, like this: Exception filtering … Read more

C# – How to use IN with Dapper

Let’s say you have a SQL Query that uses IN and you want to execute it using Dapper. Your query looks something like this: Here’s how you’d execute that with Dapper: Then you’d call it like this: There are two key things to notice about this: Exclude the parentheses In a normal SQL Query you … Read more

SqlTypeException: SqlDateTime overflow

Problem I am executing a SQL query and trying to set a datetime column to DateTime.MinValue. I’m getting the following exception: System.Data.SqlTypes.SqlTypeException: ‘SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.’ The problem is that DateTime.MinValue is 1/1/0001 12:00:00 AM and the SQL Server DateTime minimum value is 1/1/1753 12:00 AM. Solution … Read more

‘CREATE/ALTER’ must be the first statement in a query batch

Problem When you’re executing a CREATE/ALTER statement to create a procedure/view/function/trigger, you get one of the following errors: ‘CREATE/ALTER PROCEDURE’ must be the first statement in a query batch ‘CREATE VIEW’ must be the first statement in a query batch. ‘CREATE FUNCTION’ must be the first statement in a query batch. ‘CREATE TRIGGER’ must be … Read more