---
title: "Optimally Configuring Entity Framework Core - Muhammad Rehan Saeed"
description: "How to optimally configure your Entity Framework Core DbContext for best performance, resiliency and easy debugging for the developer."
canonical_url: "https://rehansaeed.com/optimally-configuring-entity-framework-core/"
last_updated: "2018-07-08T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: "Connection Strings,Entity Framework Core,Microsoft SQL Server"
  "og:description": "How to optimally configure your Entity Framework Core DbContext for best performance, resiliency and easy debugging for the developer."
  "og:image": "https://rehansaeed.com/_og/s/o_1e2d4d14e958921a.png"
  "og:image:alt": "Optimally Configuring Entity Framework Core - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Optimally Configuring Entity Framework Core"
  "twitter:image": "https://rehansaeed.com/_og/s/o_1e2d4d14e958921a.png"
  "twitter:image:alt": "Optimally Configuring Entity Framework Core - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Optimally Configuring Entity Framework Core](https://rehansaeed.com/optimally-configuring-entity-framework-core/)

Posted 8 July 2018 - **3 min read**

![Microsoft .NET](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Microsoft-.NET-1366x768.png)

Lets talk about configuring your Entity Framework Core `DbContext` for a moment. There are several options you might want to consider turning on. This is how I configure mine in most micro services:

```cs
public virtual void ConfigureServices(IServiceCollection services) =>
    services.AddDbContextPool<MyDbContext>(
        options => options
            .UseSqlServer(
                this.databaseSettings.ConnectionString,
                x => x.EnableRetryOnFailure())
            .ConfigureWarnings(x => x.Throw(RelationalEventId.QueryClientEvaluationWarning))
            .EnableSensitiveDataLogging(this.hostingEnvironment.IsDevelopment())
            .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking))
    ...
```

# Link to this sectionEnableRetryOnFailure

[EnableRetryOnFailure](https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency) enables retries for transient exceptions. So what is a transient exception? Entity Framework Core has a `SqlServerTransientExceptionDetector` class that defines that. It turns out that any `SqlException` with a very specific list of SQL error codes or `TimeoutExceptions` are considered transient exceptions and thus, safe to retry.

# Link to this sectionConfigureWarnings

By default, Entity Framework Core will log warnings when it can't translate your C# LINQ code to SQL and it will evaluate parts of your LINQ query it does not understand in-memory. This is usually catastrophic for performance because this usually means that EF Core will retrieve a huge amount of data from the database and then filter it down in-memory.

Luckily in EF Core 2.1, they added support to translate the `GroupBy` LINQ method to SQL. However, I found out yesterday that you have to write Where clauses after `GroupBy` for this to work. If you write the Where clause before your `GroupBy`, EF Core will evaluate your `GroupBy` in-memory in the client instead of in SQL. The key is to know when this is happening.

One thing you can do is throw an exception when you are evaluating a query in-memory instead of in SQL. That is what Throw on `QueryClientEvaluationWarning` is doing.

# Link to this sectionEnableSensitiveDataLogging

[EnableSensitiveDataLogging](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontextoptionsbuilder.enablesensitivedatalogging?view=efcore-2.1) enables application data to be included in exception messages. This can include SQL, secrets and other sensitive information, so I am only doing it when running in the development environment. It's useful to see warnings and errors coming from Entity Framework Core in the console window when I am debugging my application using the Kestrel webserver directly, instead of with IIS Express.

# Link to this sectionUseQueryTrackingBehavior

If you are building an ASP.NET Core API, each request creates a new instance of your `DbContext` and then this is disposed at the end of the request. Query tracking keeps track of entities in memory for the lifetime of your `DbContext` so that if they are updated any changes can be saved, this is a waste of resources if you are just going to throw away the `DbContext` at the end of the request. By passing NoTracking to the [UseQueryTrackingBehavior](https://docs.microsoft.com/en-us/ef/core/querying/tracking#no-tracking-queries) method, you can turn off this default behaviour. Note that if you are performing updates to your entities, don't use this option, this is only for API's that perform reads and/or inserts.

# Link to this sectionConnection Strings

You can also pass certain settings to connection strings. These are specific to the database you are using, here I'm talking about SQL Server. Here is an example of a connection string:

```text
Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True;Min Pool Size=3;Application Name=MyApplication
```

## Link to this sectionApplication Name

SQL Server can log or profile queries that are running through it. If you set the application name, you can more easily identify the applications that may be causing problems in your database with slow or failing queries.

## Link to this sectionMin Pool Size

Creating database connections is an expensive process that takes time. You can specify that you want a minimum pool of connections that should be created and kept open for the lifetime of the application. These are then reused for each database call. Ideally, you need to performance test with different values and see what works for you. Failing that you need to know how many concurrent connections you want to support at any one time.

# Link to this sectionThe End...

It took me a while to craft this setup, I hope you find it useful. You can find out more by reading the excellent Entity Framework Core [docs](https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext).

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 0 Comments

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/new?title=%5BComment%5D+Optimally+Configuring+Entity+Framework+Core&labels=comment)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#webpage","@type":"WebPage","dateModified":"2018-07-08T00:00:00+00:00","datePublished":"2018-07-08T00:00:00+00:00","description":"How to optimally configure your Entity Framework Core DbContext for best performance, resiliency and easy debugging for the developer.","name":"Optimally Configuring Entity Framework Core","url":"https://rehansaeed.com/optimally-configuring-entity-framework-core/","breadcrumb":{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/optimally-configuring-entity-framework-core/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#article","@type":"Article","dateModified":"2018-07-08T00:00:00+00:00","datePublished":"2018-07-08T00:00:00+00:00","description":"How to optimally configure your Entity Framework Core DbContext for best performance, resiliency and easy debugging for the developer.","headline":"Optimally Configuring Entity Framework Core","inLanguage":"en-GB","url":"https://rehansaeed.com/optimally-configuring-entity-framework-core/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Microsoft-.NET-1366x768.png","caption":"Microsoft .NET","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#webpage"},"keywords":["Connection Strings","Entity Framework Core","Microsoft SQL Server"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/optimally-configuring-entity-framework-core/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Optimally Configuring Entity Framework Core","item":"https://rehansaeed.com/optimally-configuring-entity-framework-core/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
