EF Core save built model for subsequent startup
See original GitHub issueHi,
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:
- Created 2 years ago
- Comments:24 (12 by maintainers)
@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?
Seems no way. Thanks