Make your EF Query logs traceable

If you are a .NET developer, there is high chance that you’ve spent way too much time looking at Entity Framework logs to understand and investigate generated queries. Probably one of the most time-consuming tasks is to find out what has been translated to what especially when it comes to complex chatty solutions. Entity Framework Core 2.2 introduced a new feature called Query Tags which can be used to tag queries and make the output traceable. You simply can annotate your LINQ queries using TagWith() method.

Let’s have a look at an example. In the following example, I annotated my query with “List of top 10 books”:

var books =
      (from b in DbContext.Books.TagWith(@"List of top 10 books")
      orderby b.Price descending
      select b).Take(10).ToList();

And here is the query output in the the log:

-- List of top 10 books
 
SELECT TOP(@__p_1) [b].[Id], [b].[Name], [b].[Price]
FROM [Books] AS [b]
ORDER BY [b].[Price] DESC

Now as a developer, I can easily find out my query output in logs without burning calories!

Seeding data in EF Core 2.1

Microsoft announced Entity Framework Core 2.1 RC in Build 2018. Data Seeding probably is one of the most useful features of Entity Framework and it got a nice upgrade on this version. Unlike Entity Framework 6.0, Seeding data is associated with an entity type as part of the model configuration which means Entity Framework can now track added, updated or removed data from one change to another change and generates the corresponding migration script for the changes.

Seeding data in Entity Framework Core now is as easy as:

modelBuilder.Entity<Book>().HasData(new Book {BookId = 1, Title = "Don't read this book"});