Blog

Query Tags in EF Core for DotNet Core

By 4 January 2021 January 7th, 2021 No Comments

Query Tags in EF Core for DotNet Core

How to implement Query Tags

Sharing is caring!

Query tags is introduced in entity framework(EF) core 2.2. Query tags helps when browsing logs during debugging and troubleshooting on Linq query. LINQ added new method for query tag as TagWith().TagWith() method take only one paramter as string and that string showing on browsing logs during debugging and troubleshooting of linq query.

How to Implement Query Tags?

You can check existing database or with new database. Here I am creating new database with new table ContactUs
public class ContactUs
    {
        [Key]  // for primary key
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //for primary key auto increment
        public int ID { get; set; }
        public string Name { get; set; }
        public string MobileNo { get; set; }
        public string Message { get; set; }
        public DateTime CreatedDate { get; set; }
    }
For CodeFirst Approach add in Context class
public   DbSet<ContactUs> ContactUs { get; set; }
I created one controller (Admin) and action (Index) method and write a query for fetch data from database.
public class AdminController : Controller
    {
        private readonly ApplicationDbContext _context; // database context

        public AdminController(ApplicationDbContext context)
        {
            _context = context;
        }
        public async Task<IActionResult> Index()
        {

            var result = (from contact in _context.ContactUs
                    .TagWith($"Take only top {2} records!")
                          orderby contact.CreatedDate ascending
                          select contact)
                    .Take(2);

            return View(result);
        }
    }
On above linq query, Tagwith() method take single parameter as string and that string showing in SQL Server Profiler. As I added TagWith string $”Take only top {2} records!” will display on profile after executing Index method, In $”Take only top {2} records!” string I added dollar sign($) to identify a sting literal as an interpolated string. In C# 6 introduce new feature known as string interpolation is a method of concatenation, formatting and manipulation strings.

How to see logs on profiler

First go to SQL Server Profiler and connect with database after that create new trace Run you dotnet core project where we write linq query with TagWith() method You can see the following output:blank [/vc_column_text]
Query Tags in EF Core for DotNet Core
[/vc_column][/vc_row]

Leave a Reply

Get started with Bloom