/// <summary> /// Returns the model from the cache, or creates a model if it is not present in the cache. /// </summary> /// <param name="context"> The context the model is being produced for. </param> /// <param name="conventionSetBuilder"> The convention set to use when creating the model. </param> /// <param name="modelDependencies"> The dependencies object for the model. </param> /// <returns> The model to be used. </returns> public virtual IModel GetModel( DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies) { var cache = Dependencies.MemoryCache; var cacheKey = Dependencies.ModelCacheKeyFactory.Create(context); if (!cache.TryGetValue(cacheKey, out IModel model)) { // Make sure OnModelCreating really only gets called once, since it may not be thread safe. lock (_syncObject) { if (!cache.TryGetValue(cacheKey, out model)) { model = CreateModel(context, conventionSetBuilder, modelDependencies); model = cache.Set(cacheKey, model, new MemoryCacheEntryOptions { Size = 100, Priority = CacheItemPriority.High }); } } } return(model); }
/// <summary> /// Creates the model. This method is called when the model was not found in the cache. /// </summary> /// <param name="context"> The context the model is being produced for. </param> /// <param name="conventionSetBuilder"> The convention set to use when creating the model. </param> /// <param name="modelDependencies"> The dependencies object for the model. </param> /// <returns> The model to be used. </returns> protected virtual IModel CreateModel( [NotNull] DbContext context, [NotNull] IConventionSetBuilder conventionSetBuilder, [NotNull] ModelDependencies modelDependencies) { Check.NotNull(context, nameof(context)); var modelBuilder = new ModelBuilder(conventionSetBuilder.CreateConventionSet(), modelDependencies); Dependencies.ModelCustomizer.Customize(modelBuilder, context); return(modelBuilder.FinalizeModel()); }