question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

EF Core save built model for subsequent startup

See original GitHub issue

Hi, I have read, at the following link https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-6-0-preview-5-compiled-models/,
the proposed solution on version 6 for improving speed on startup of application that is using EF Core. For what I understood the solution provide a mechanism using the EF Core tools Command Line Interface (CLI) to pre-build model during code compile time. Unfortunately this solution, at least for what I understood, does not cover scenario where the final model depends from the database schema version to which the EF Core is connecting to, information available only during runtime. This scenario frequently happens when application want support different database schema versions. So what I propose is a solution, here below, that could expose some APIs for making persistent the compiled model:

string tenant = SomeServices.GetConfiguredTenant();
var connection = Microsoft.Data.SqlClient.SqlClientFactory.Instance.CreateConnection();
connection.ConnectionString = "<connection_string>"
			
ISerializedModel serializedModel; // Example of proposed solution:  have a serializable class of the compiled model
IModel model;

var optionBuilder = new DbContextOptionsBuilder();
optionBuilder.UseLazyLoadingProxies(true);
optionBuilder.UseLoggerFactory(loggerFactory);

if (!SomePersistentCacheService.Get($"{tenant}.model", out serializedModel))
{	
    connection.Open();
    string version;
     using (var cmd = connection.CreateCommand())
     {
	  cmd.CommandText = "SELECT VERSION FROM MYINSTALLEDSCHEMAVERSION";
	  version = (string) cmd.ExecuteScalar();
     }
     connection.Close();

     var modelBuilder = new ModelBuilder(SqlServerConventionSetBuilder.Build());

     modelBuilder.HasDefaultSchema("AMOS");
     modelBuilder.Entity<AMOS_ADDRESS>(b => b.ToTable("ADDRESS"));
     modelBuilder.Entity<AMOS_ADDRESS>().HasKey(e => e.ADDRESSID);
				
     // An example of a model change based on database schema version
     if (version >= "v.1.0")
	modelBuilder.Entity<AMOS_ADDRESS>().Property(e => e.CODE).HasColumnName("CODE");
     else
         modelBuilder.Entity<AMOS_ADDRESS>().Ignore(e => e.CODE);

      // Other entities and properties model setting

      model = modelBuilder.FinalizeModel();
      SomePersistentCacheService.GetOrCreate($"{tenant}.model", () => model.GetSerializedModel());
 }
 else
      model = serializedModel.GetModel();
			
 optionBuilder.UseModel(model);
 optionBuilder.UseSqlServer(connection);

 using (var dbContext = new DbContext(optionBuilder.Options))
  {
				
  }

Thanks in advance for the answer. Regards Luigi

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:24 (12 by maintainers)

github_iconTop GitHub Comments

1reaction
ajcvickerscommented, Oct 1, 2021

@Luigi6821 I think the thing that I don’t fully understand is how the schema is changing but the mappings are not changing. Typically if the schema is different, then the mappings in code also need to be different. Can you give an example of where the schema changes but this does not require the mappings to change?

0reactions
Luigi6821commented, Oct 9, 2021

Seems no way. Thanks

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why is saving a single entity to my EF Core database ...
Once the entity is created and .SaveChanges() has been applied, the model has links to all other entities as expected. It seems I...
Read more >
Announcing Entity Framework Core 6.0 Preview 5
Compiled models dramatically reduce startup time for your application. The models are generated (similar to how migrations are) so they should ...
Read more >
Entity Framework Core with Existing Database
Creating a Model for an Existing Database in Entity Framework Core ... Here you will learn how to create the context and entity...
Read more >
Best Practices in Using the DbContext in EF Core
This article is about DbContext concepts and the best practices you can adhere to for improving the performance of your applications built ......
Read more >
Applying Seed Data To The Database
One way to seed data in EF Core is by using the DbContext. Database. EnsureCreated() method in your DbContext class. This method will...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found