I want to analyse in this post how Entity Framework really interact with the database. i.e. The queries that are really executed.
In previous post I created a database using Code First. These are two of my entities:
A food representation:
public class Food { /// <summary> /// Gets or sets the food identifier. /// </summary> [Key] // NOTE: As the name is className + id, this property is not needed public int Id { get; set; } /// <summary> /// Gets or sets the food name. /// </summary> [MaxLength(200)] [Index(IsUnique = true)] public string Name { get; set; } /// <summary> /// Gets or sets the recipes needing this Food /// </summary> // NOTE: EF needs the virtual attribute to enable Lazy loading public virtual List<Recipe> RecpiesNeedingThisFood { get; set; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> public override string ToString() { return string.Format("{0} ({1})", this.Name, this.Id); } }
An entry on my fridge representation: a food and an expire date of this food.
public class FridgeEntry { /// <summary> /// Initializes a new instance of the <see cref="FridgeEntry"/> class. /// </summary> public FridgeEntry() { ExpireDate = DateTime.MaxValue; } public int Id { get; set; } [Required] // NOTE virtual is needed for lazy loading public virtual Food Food { get; set; } /// <summary> /// Gets or sets the expire date. /// </summary> public DateTime ExpireDate { get; set; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> public override string ToString() { return string.Format("FoodId ({0}) - expire date: {1}", this.Id, this.ExpireDate); } }
How to debug the queries and connections between EF and my database?
A new feature of EF6 is the possibility to log everything that Entity Framework is doing.
The context.Database has a Log property which is type Action<string> if this action is not null EF will call it always he connect to the database.
Define a logger, to analyse the Lazy loading a simple method writing in console the messages is enough:
private static void ConsoleLogger(string msg) { msg = msg.Trim(); if (!string.IsNullOrEmpty(msg)) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(DateTime.Now.TimeOfDay.ToString("g")); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(msg); Console.ResetColor(); } }
Now we just have to define this logger as the logger of the context.Database.
EF Lazy loading testing
We have already a way to see the connections between EF and the database, now let’s analyse it: