EF Core’s IsConfigured and Logging

I got a little confused about some behavior today and finally realized my mistake so thought I would share it. This mostly happens in demo apps that I’m building that are not using  ASP.NET Core.


In these cases, I typically stick the DbContext provider configuration in the OnModelConfiguring method. For example, if I’m using SQLite, then I would specify that in the method as such:


protected override void OnConfiguring
 (DbContextOptionsBuilder optionsBuilder)
{
  optionsBuilder.UseSqlite (@"Filename=Data/PubsTracker.db");
}

I also have been using the logging factory a lot. After defining it, I also configure it. I hadn’t thought much about where I was placig it so added it in randomly.


protected override void OnConfiguring
(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory (MyConsoleLoggerFactory);
optionsBuilder.UseSqlite (@"Filename=Data/PubsTracker.db");
}

Then I added in some tests to had to avoid the SQLite provider if the InMemory provider was already configured, so I wrapped the UseSqlite method with a check to see if the options builder was already configured.


protected override void OnConfiguring
(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory (MyConsoleLoggerFactory);
if(!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite (@"Filename=Data/PubsTracker.db");
}
}

But my logic wasn’t working. I was running some migrations but they were suddenly not recognizing the UseSqlite method. I’ve used this pattern so many times. It took me a while to realize what was going on. The UseLoggerFactory is a configuration!


I just had to move the UseLoggerFactory logic after the IsConfigured check and all was well.


This is one of those dumb things that seems so silly you wouldn’t imagine someone else would make such a mistake. But since it bit me, I thought it was worth sharing mostly for the sake of the next coder who is trying to solve the same problem.


 •  0 comments  •  flag
Share on Twitter
Published on June 14, 2018 14:18
No comments have been added yet.


Julia Lerman's Blog

Julia Lerman
Julia Lerman isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Julia Lerman's blog with rss.