C# – Enum generic type constraint

Here’s how you can use Enum as a generic constraint: Note: Microsoft added this feature in C# 7.3. Whenever you have a generic method, it’s a good idea to use generic type constraints. Without constraints, you would have to implement type checking in the generic method and throw exceptions if an invalid type was used. … Read more

SqlException: Cannot insert explicit value for identity column

When you have a table with an identity column, and you try to specify the value for identity column when inserting a record, you’ll get the following exception: Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table ‘Movies’ when IDENTITY_INSERT is set to OFF. This error means you have an identity column in … Read more

C# – Conditional compilation

You can exclude specific code from being compiled by using conditional compilation symbols. There are a few predefined symbols that support common scenarios – conditional compilation based on target framework (ex: .NET 5 vs .NET Core 3.1) and based on build configuration (Debug vs Release). In addition, you can add your own symbols to handle … Read more

C# – Remove a list of characters from a string

When you want to remove a list of characters from a string, loop through the list and use string.Replace(): Note that string.Replace() returns a new string (because strings are immutable). Running this outputs the following: This is the fastest approach (in .NET 6+). Linq approach: Where() + ToArray() + new string() Another option for removing … Read more

C# – Get all loaded assemblies

You can get all of the loaded assemblies with AppDomain.CurrentDomain.GetAssemblies(). Here’s an example of looping over all loaded assemblies and outputting their metadata: Note: This is outputting an interpolated string to the console. This outputs the following information: I’ll show more examples of how you can use the assembly information. Get custom assembly attributes Assembly … 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 – 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

EF Core – How to add indexes

In this article, I’ll show how to add indexes using EF Core. If you’re not sure about why you would need indexes, take a look at this article explaining how indexes greatly improve query performance. Add an index with a single column The simplest way to add an index is to by adding the [Index] … Read more

EF Core – Add a foreign key

In this article, I’ll show how to add a foreign key using EF Core. Then I’ll show how foreign keys affect inserts and deletes. How to add a foreign key A Show has one or more Episodes. In this section, I’ll show how to link these two tables together to enforce the 1-to-many relationship. In … Read more

EF Core – Apply migrations programmatically

In EF Core, you create migrations when you are first creating the database and tables and also for any database schema changes. DbContext.Database has a few methods you can call to manage migrations programmatically. To apply any pending migrations: If the database doesn’t exist, MigrateAsync() will create it and then apply the migrations. To check … Read more

EF Core – Database schema changes

Anytime you change the definition of the database – from renaming a column to creating a table – it’s referred to as a database schema change. With EF Core, you deal with database schema changes by using migrations. When you first create the database with EF Core, you create a migration that contains the initial … Read more

Feature flags in ASP.NET Core

In this article, I’ll show an example of using a feature flag to toggle an endpoint on/off with a configuration value in appsettings.json. 1 – Install feature management package Install the Microsoft.FeatureManagement.AspNetCore nuget package. Note: This is using (View > Other Windows > Package Manager Console). 2 – Add feature flags to appsettings.json Edit appsettings.json … 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# – Closures capture variables, not values

Let’s say you’re firing off Task.Run() a bunch of times in a loop and passing in the loop variable, like this: The natural assumption is that this will print out 0 through 9. But instead, it’s printing out ten 10’s: This is a common mistake, especially when using Task.Run() in a loop. What’s happening here … Read more

NLog – Archive by file size

To archive by file size when you’re using NLog, you can configure nlog.config like this: You specify archiveAboveSize in bytes. The above configuration is specifying ~1 MB. When your log file hits the specified size, NLog will “archive” the file, which really just means it will rename the log file and start a new log … Read more

CA1062: Validate parameter is non-null before using it

When you have a public method that isn’t null checking its parameters, then you’ll get the CA1062 code analysis warning. For example, the following code isn’t null checking the movieRepository parameter: This results in the CA1062 code analysis warning: CA1062 In externally visible method ‘void StreamingService.LogMovies(MovieRepository movieRepository)’, validate parameter ‘movieRepository’ is non-null before using it. … Read more