How to mock an async repository with Entity Framework Core

Thanks to @Nkosi for pointing me to a link with an example of doing the same thing in EF 6: https://msdn.microsoft.com/en-us/library/dn314429.aspx. This didn’t work exactly as-is with EF Core, but I was able to start with it and make modifications to get it working. Below are the test classes that I created to “mock” IAsyncQueryProvider: … Read more

Entity Framework Core 2.0.1 Eager Loading on all nested related entities

Such feature officially does not exist currently (EF Core 2.0.2 and also the incoming 2.1). It’s been requested in Eager load all navigation properties #4851(Closed) and currently is tracked by Rule-based eager load (include) #2953 and Allow for declaring aggregates in the model (e.g. defining included properties or by some other means) #1985 (both in … Read more

Dynamically change connection string in Asp.Net Core

This is enough if you want to choose a connection string per http request, based on the active http request’s parameters. using Microsoft.AspNetCore.Http; //.. services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddDbContext<ERPContext>((serviceProvider, options) => { var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext; var httpRequest = httpContext.Request; var connection = GetConnection(httpRequest); options.UseSqlServer(connection); }); Update A year or so later, my solution looks like bits … Read more

Get SQL code from an Entity Framework Core IQueryable

EF core 5/6 / Net 5/6 query.ToQueryString() See Documentation ToQueryString() and What’s New in EF Core 5.0 var query = _context.Widgets.Where(w => w.IsReal && w.Id == 42); var sql = query.ToQueryString(); For older net core frameworks an Extension can be used. Core 2.1.2 using System.Linq; using System.Reflection; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Query.Expressions; using Microsoft.EntityFrameworkCore.Query.Sql; … Read more

EF Core Second level ThenInclude missworks

This is a known Intellisense issue with the ThenInclude overload for collection type navigation properties, tracked by the Completion missing members of lambda parameter in fault tolerance case #8237 Roslyn GitHub issue. Until it gets fixed, simply type the name of the property and it will compile successfully and work as expected. .ThenInclude(mu => mu.ParseSubTrees) … Read more

EF Core returns null relations until direct access

The reason is explained in the Loading Related Data section of the EF Core documentation. The first behavior is because EF Core currently does not support lazy loading, so normally you’ll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following: Tip … Read more