efcore: Error running EnsureCreated(). What am I doing wrong?

Hello! I tried to use EnsureCreated in my Startup.cs, Configure()-method.

using var scope = app.ApplicationServices.CreateScope();
using var context = scope.ServiceProvider.GetService<WPContext>();
context.Database.EnsureDeleted();            
context.Database.EnsureCreated();

Throws this exception:

System.InvalidOperationException: 'The requested configuration is not stored in the read-optimized model, please use 'DbContext.DesignTimeModel'.'

Stack trace

   at Microsoft.EntityFrameworkCore.Metadata.SlimEntityType.Microsoft.EntityFrameworkCore.Metadata.IReadOnlyEntityType.GetSeedData(Boolean providerValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.TrackData(IRelationalModel source, IRelationalModel target, DiffContext diffContext)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.<GetDataOperations>d__74.MoveNext()
   at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IRelationalModel source, IRelationalModel target)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.GetCreateTablesCommands(MigrationsSqlGenerationOptions options)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.CreateTables()
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
   at WorkPartnerLib.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, IHubContext`1 baseHub, IDistributedCache cache, IHttpContextAccessor httpContextAccessor) in C:\Users\utvec\Programmering\WorkPartnerLib\WorkPartnerLib\Startup.cs:line 187
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__34.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at WorkPartnerLib.Program.Main(String[] args) in C:\Users\utvec\Programmering\WorkPartnerLib\WorkPartnerLib\Program.cs:line 17

Version

EF Core version: 6.0 preview4 (tried with preview5 also). Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 6.0 Operating system: Windows 10 IDE: Visual Studio 2022 Preview

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 17 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Should we add an example to the docs? (If it’s not there already.)

If you have a custom IModelCacheKeyFactory implementation make sure to implement the new overload.

@lucianbrezaiu The easiest is a tuple (context.GetType(), designTime). But otherwise any type that uses the values of context.GetType() (if you use more than one DbContext type in the application) and designTime in Equals and GetHashCode should work.

As @hounddog22030 showed a string value can also be constructed, but this is less recommended as it causes additional allocations.

I am experiencing this problem. I have reviewed the “New IModelCacheKeyFactory implementation”, but frankly I don’t understand what it is doing or why…

Our exception is:

Message: 
System.InvalidOperationException : The requested configuration is not stored in the read-optimized model, please use 'DbContext.GetService&lt;IDesignTimeModel&gt;().Model'.

  Stack Trace: 
IReadOnlyEntityType.GetSeedData(Boolean providerValues)
InMemoryStore.EnsureCreated(IUpdateAdapterFactory updateAdapterFactory, IModel designModel, IDiagnosticsLogger`1 updateLogger)
InMemoryDatabase.EnsureDatabaseCreated()
InMemoryDatabaseCreator.EnsureCreated()
DatabaseFacade.EnsureCreated()
DataContextHelper.GetTestAutoPartsContext(String tenantId) line 44
MakeInfoHelperTest.SimpleTest() line 20
<>c.<ThrowAsync>b__128_0(Object state)

We are using the in memory database via

optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString())

Our IModelCacheKeyFactory is as follows:

public class ClaimsPrincipalModelKeyFactory : IModelCacheKeyFactory
{
    public object Create(DbContext context) => Create(context, false);
    public object Create(DbContext context, bool designTime)
    {
        var claims = ((ContextBase) context).Claims;
        string returnValue = string.Empty;

    var enumerable = claims as Claim[] ?? claims.ToArray();
    if (enumerable.TryGetNameTenantId(out Guid tenantId))
    {
        returnValue += tenantId.ToString();
    }
    if (enumerable.TryGetAmazonSellerId(out string sellerId))
    {
        returnValue += sellerId;
    }
    if (enumerable.TryGetNameIdentifier(out string nameIdentifier))
    {
        returnValue += nameIdentifier;
    }

    if (string.IsNullOrEmpty(returnValue))
    {
        throw new InvalidOperationException($"Unable to determine {nameof(ClaimsPrincipalModelKeyFactory)}");
    }

    return returnValue;
}

}

Everything is updated to latest (6.0.2)

What should I be looking @?