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# – Execute a stored procedure with Dapper

You can execute stored procedures with Dapper by specifying the name, parameters, and CommandType.StoredProcedure. Let’s say you have the following stored procedure (single parameter, returns movie rows): Here’s how to execute this stored procedure with Dapper and map its results to Movie objects: Use an output parameter To get a stored procedure’s output parameter, add … Read more

SQL – Aggregate functions with GROUP BY

There are five main aggregate functions in SQL: COUNT(), SUM(), AVG(), MIN(), and MAX(). These calculate aggregate values for sets of rows. When you use them with GROUP BY, they calculate the aggregate values for each group. Let’s say you want to get movie streaming stats for each user. Here’s an example of using GROUP … Read more

C# – Connect to a MySQL database

The simplest way to connect to a MySQL database in a .NET project is to use the MySql.Data package (from Oracle). It provides classes that implement the standard ADO.NET interfaces (such as IDbConnection). First, add the MySql.Data package to your project (this is using View > Other Windows > Package Manager Console): Now use the … 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

SQL Server – Copy data from one table to another

To copy data from one table to an existing table, use INSERT INTO SELECT and specify the column list: If the columns are the exact same in the two tables (and there are no identity columns), you don’t need to specify the column list: When the table doesn’t exist, use SELECT INTO, specifying which columns … 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# – Execute a SELECT query with Dapper

You can query the database with Dapper by using Query() with a SELECT, specifying the type to map the results to, and optionally adding parameters. Here’s an example: Note: It returns an empty list when there’s no results. Dapper abstracts away the repetitive code involved in executing SQL queries, including mapping parameters and query results. … Read more

EF Core – Inheritance mapping

There are two ways to do inheritance mapping in EF Core: Let’s say we have a database with employees. All employees have an id and a name. There are currently two types of employees: programmers and drivers. Programmers have a language (ex: C#), and drivers have a car (ex: Honda). We can model this with … Read more

C# – How to match an anonymous type parameter in a mocked method

When an anonymous type is defined in one assembly, it won’t match an anonymous type defined in another assembly. This causes problems when you’re unit testing and trying to mock a method that has an anonymous type parameter. For example, let’s say you’re trying to unit test the following method: To unit test this, you … Read more

Get SQL Server query results as JSON

The simplest way to get query results as JSON is to use FOR JSON PATH in the query (note: this was added in SQL Server 2016): It returns the results as a single JSON string with one JSON object per row: Note: SQL Server returns the JSON without indenting. All examples in this article show … Read more

SQL – Select from information_schema.columns

You can query the information_schema.columns system view to get information about all columns in the database. Here’s an example: Here’s the first few rows this returns: TABLE_NAME COLUMN_NAME Movies Id Movies Title Movies Year In this article, I’ll show more examples of querying information_schema.columns. Get columns filtered by name Let’s say you want to find … Read more

Case sensitivity in SQL Server

In SQL Server, the collation property controls case sensitivity. Case sensitivity affects sorting and queries (even the column names must match exactly if you’re using a case-sensitive collation at the database-level). The default collation when you create a database in SQL Server is SQL_Latin1_General_CP1_CI_AS. The CI stands for case-insensitive, which means SQL Server databases are … Read more

EF Core – Aggregate SELECT queries

In this article, I’ll show how to use EF Core to aggregate data for the whole table, per group, and how to only include groups that meet a condition. I’ll show three different SQL aggregate functions – count, sum, and average. In each scenario, I’ll show the LINQ query, the SQL query it generated, and … Read more

EF Core – SELECT queries involving multiple tables

When you’ve created tables that are related, you’ll often need to get data from both tables at once, or filter records from one table based on values in another table. In this article, I’ll show examples of executing queries like this where more than one table is involved. You can do most queries using LINQ. … Read more

EF Core – Basic SELECT queries

In this article, I’ll show examples of how to execute basic SELECT queries when using EF Core. You can execute queries using LINQ or by writing raw SQL. I’ll use SQL Profiler to show the queries generated by LINQ. Note: I’ll be using .AsNoTracking().ToListAsync() in all cases. You’ll need to decide if that’s the right … Read more

EF Core – How to add a computed column

To add a computed column in EF Core, override DbContext.OnModelCreating() and specify the computed column using ModelBuilder, like this: In this article, I’ll show a full example of adding a computed column and then show how to specify that the computed column should be persisted. Example of adding a computed column Let’s say we have … Read more

Cannot drop database because it is currently in use

Problem When you try to drop the database, you get the following error and the drop fails: Cannot drop database because it is currently in use. This means there are other open connections on the database and it won’t let you drop the database. Disclaimer: The solutions in this article involve kicking out other active … Read more

SQL Server – Getting and storing date/time

In this article, I’ll show built-in functions in SQL Server for getting the current datetime and how to get individual parts of the datetime (such as the year). Then show I’ll show how to store datetimes using the four different date/time data types (date, time, datetime2, and datetimeoffset). Getting the current datetime SQL Server has … 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