// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Common; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; namespace EFIntercept { [Table("t1")] public class T1 { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("f1")] public int F1 { get; set; } [Column("f2")] public string F2 { get; set; } public T1() : this(0, "") { } public T1(int f1, string f2) { F1 = f1; F2 = f2; } public override string ToString() { return string.Format("[{0},{1}]", F1, F2); } } public class MyInterceptor : DbCommandInterceptor { public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result) { Console.WriteLine(command.CommandText); Console.WriteLine("{0} {1}", eventData.StartTime, eventData.Duration); Console.WriteLine(result.HasRows); return base.ReaderExecuted(command, eventData, result); } } public class MyDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=ARNEPC5\SQLEXPRESS;Integrated Security=true;Database=Test").AddInterceptors(new MyInterceptor()); } public DbSet T1 { get; set; } } public class Program { public static void Main(string[] args) { using (MyDbContext db = new MyDbContext()) { foreach(T1 o in db.T1) { Console.WriteLine(o); } } } } }