efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Optimize-DbContext in Core 7 preview 6 fails with get_ServiceOnlyConstructorBinding() method not found error

Open ronymeyer opened this issue 3 years ago • 6 comments

When running Optimize-DbContext in the VS 2022 package manager console with entity framework core 7.0.0-preview.6.22329.4 it errors with:

System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.InstantiationBinding Microsoft.EntityFrameworkCore.Metadata.Internal.IRuntimeEntityType.get_ServiceOnlyConstructorBinding()'. at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpRuntimeModelCodeGenerator.Create(IEntityType entityType, CSharpRuntimeAnnotationCodeGeneratorParameters parameters) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpRuntimeModelCodeGenerator.CreateEntityType(IEntityType entityType, IndentedStringBuilder mainBuilder, IndentedStringBuilder methodBuilder, SortedSet`1 namespaces, String className, Boolean nullable) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpRuntimeModelCodeGenerator.GenerateEntityType(IEntityType entityType, String namespace, String className, Boolean nullable) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpRuntimeModelCodeGenerator.GenerateModel(IModel model, CompiledModelCodeGenerationOptions options) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CompiledModelScaffolder.ScaffoldModel(IModel model, String outputDir, CompiledModelCodeGenerationOptions options) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.Optimize(String outputDir, String modelNamespace, String contextTypeName) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContextImpl(String outputDir, String modelNamespace, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContext.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Method not found: 'Microsoft.EntityFrameworkCore.Metadata.InstantiationBinding Microsoft.EntityFrameworkCore.Metadata.Internal.IRuntimeEntityType.get_ServiceOnlyConstructorBinding()'.

Running the same with preview 5 works.

ronymeyer avatar Jul 29 '22 14:07 ronymeyer

@ronymeyer Please post your csproj file.

ajcvickers avatar Jul 29 '22 14:07 ajcvickers

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <OutputType>Library</OutputType>
    <RootNamespace>FinanceKey.Entity</RootNamespace>
    <AssemblyName>FinanceKeyEntity</AssemblyName>
    <GenerateAssemblyInfo>true</GenerateAssemblyInfo>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject />
    <UserSecretsId>aspnet-MVC-4E188E23-AC82-4A7B-8484-21A86AB16794</UserSecretsId>
    <CodeAnalysisRuleSet>..\.sonarlint\financekey_financekeycsharp.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Compile Remove="Connectivity\**" />
    <EmbeddedResource Remove="Connectivity\**" />
    <None Remove="Connectivity\**" />
  </ItemGroup>
  <ItemGroup>
    <AdditionalFiles Include="..\.sonarlint\financekey_financekey\CSharp\SonarLint.xml" Link="SonarLint.xml" />
  </ItemGroup>
  <ItemGroup>
    <None Include="..\.editorconfig">
      <Link>.editorconfig</Link>
	  <Link_TypeName>System.String</Link_TypeName>
    </None>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-preview.6.22329.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="7.0.0-preview.6.22329.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.0-preview.6.22329.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0-preview.6.22329.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0-preview.6.22329.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0-preview.6.22324.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0-preview.6.22324.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0-preview.6.22324.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0-preview.6.22324.4" />
    <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Interop" Version="17.2.32505.113" />
    <PackageReference Include="System.ComponentModel.Annotations" Version="6.0.0-preview.4.21253.7" />
    <PackageReference Include="System.Text.Json" Version="7.0.0-preview.6.22324.4" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Audit\Generated\" />
  </ItemGroup>
</Project>

ronymeyer avatar Jul 29 '22 15:07 ronymeyer

@ronymeyer Are you deleting the existing compiled model before running Optimize-DbContext again? If not, can you try that?

ajcvickers avatar Aug 02 '22 19:08 ajcvickers

It's a brand new compiled model. We didn't use it before as we use proxy entities, which is now supported in this preview. I disabled proxy entities and was able to create the compiled model with preview 5, however with preview 6 I'm getting this error with or without proxy entities.

ronymeyer avatar Aug 02 '22 19:08 ronymeyer

@ronymeyer Thanks. We will investigate.

ajcvickers avatar Aug 02 '22 19:08 ajcvickers

@ronymeyer I am not able to reproduce this. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

Here's my code, and output from compiling the model:

public static class Your
{
    public static string ConnectionString = @"Data Source=(LocalDb)\MSSQLLocalDB;Database=Test";
}

public class Blog
{
    public int Id { get; set; }
    public string? Title { get; set; }

    public virtual ICollection<Post> Posts { get; } = new List<Post>();
}

public class Post
{
    public int Id { get; set; }
    public virtual Blog? Blog { get; set; }
}

public class SomeDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer(Your.ConnectionString)
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    public DbSet<Blog> Blogs { get; set; } = null!;
    public DbSet<Post> Posts { get; set; } = null!;
}

public class Program
{
    public static void Main()
    {
        using (var context = new SomeDbContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(new Blog { Posts = { new Post(), new Post() } });

            context.SaveChanges();
        }

        using (var context = new SomeDbContext())
        {
            var blog = context.Blogs.Single();
            Console.WriteLine(blog.Posts);
        }
    }
}
PM> Optimize-DbContext
Build started...
Build succeeded.
8/8/2022 16:20:31.092 CoreEventId.SensitiveDataLoggingEnabledWarning[10400] (Microsoft.EntityFrameworkCore.Infrastructure) 
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
8/8/2022 16:20:31.208 CoreEventId.ContextInitialized[10403] (Microsoft.EntityFrameworkCore.Infrastructure) 
      Entity Framework Core 7.0.0-preview.6.22329.4 initialized 'SomeDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:7.0.0-preview.6.22329.4' with options: SensitiveDataLoggingEnabled 
Successfully generated a compiled model, to use it call 'options.UseModel(SomeDbContextModel.Instance)'. Run this command again when the model is modified.
PM> 

ajcvickers avatar Aug 08 '22 15:08 ajcvickers

Thank you for investigating this @ajcvickers. When trying to create a project to reproduce this I saw that preview 7 was released and first tried with that one. Looks like the issue is fixed in preview 7. We have a few other issues, but I will create a seperate thread for those and close this one here.

ronymeyer avatar Aug 11 '22 11:08 ronymeyer