Troubleshooting - MikeHanson/NLog.Mvc GitHub Wiki

LoggingContext has changed error

UPDATE: I added the SetInitializer call to LogEntryConfiguration in the 1.0.0.4 NuGet package because I was experiencing this exception still once I added code that added a log entry before I had used my application DbContext

If you are integrating NLog.Mvc with a project or solution that already has a DbContext and you have used Code First/Migrations to create the database then you may get an exception when you try to log. This is because at the time the in memory model is built the metadata that is expected for LoggingContext is not present in the database. Basically you have to tell the model builder that it should not look for the metadata by setting the initialiser for LoggingContext to null with the following statement:

    Database.SetInitializer<LoggingContext>(null);

For example in a project I have a ModelContext defined like this:

public class ModelContext : DbContext, IModelContext
{
	public IDbSet<User> Users { get; set; }
	public IDbSet<Role> Roles { get; set; }
	
	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		Database.SetInitializer<LoggingContext>(null);

		modelBuilder.Configurations.Add(new UserConfiguration());
		modelBuilder.Configurations.Add(new RoleConfiguration());
		modelBuilder.Configurations.Add(new LogEntryConfiguration());
	}
}

Here the DbContext is defined to provide the Users and Roles collections, but addittionally includes the configuration for LogEntry entities. Notice the first statement in the overload of OnModelCreating, without this I was getting the exception suggesting my model had changed since the database was created.

⚠️ **GitHub.com Fallback** ⚠️