Skip to content

'The object has been removed from the model.' when building model #26659

Closed

Description

This issue is similar to #25138 but is happening when the owned types are nested. This is happening when configuring the second, nested, owned type, each of which are the same .NET type, and the first owned type is using HasIndex.

Code to Reproduce

async Task Main() {
    var services = new ServiceCollection();

    services.AddDbContext<ApplicationContext>(db => {
        //db.UseSqlServer(@"Server=(localdb)\mssqllocaldb; Database=test; Trusted_Connection=True; MultipleActiveResultSets=true")
        //    .EnableDetailedErrors()
        //    .EnableSensitiveDataLogging();
        db.UseInMemoryDatabase(Guid.NewGuid().ToString());
    });

    using var root = services.BuildServiceProvider();
    using var scope = root.CreateScope();

    var db = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
    //await db.Database.EnsureDeletedAsync();
    await db.Database.EnsureCreatedAsync();
}

public class ApplicationContext : DbContext {
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options) {
    }

    public DbSet<Customer> Customers { get; set; } = default!;
    public DbSet<Author> Authors { get; set; } = default!;

    protected override void OnModelCreating(ModelBuilder model) {
        model.Entity<Customer>(customer => {
            customer.OwnsOne(x => x.Contacts, contacts => {
                contacts.OwnsOne(x => x.PrimaryContact, primaryContact => {
                    primaryContact.HasIndex(x => x.PhoneNumber);
                });
                
                contacts.OwnsOne(x => x.SecondaryContact, secondaryContact => {
                    secondaryContact.HasIndex(x => x.PhoneNumber);
                });
            });
        });
        
        model.Entity<Author>(author => {
            author.OwnsOne(x => x.Contacts, contacts => {
                contacts.OwnsOne(x => x.PrimaryContact, primaryContact => {
                    primaryContact.HasIndex(x => x.PhoneNumber);
                });

                contacts.OwnsOne(x => x.SecondaryContact, secondaryContact => {
                    secondaryContact.HasIndex(x => x.PhoneNumber);
                });
            });
        });
    }
}

public sealed class Customer {
    public Guid CustomerId { get; init; } = default!;
    public Contacts Contacts { get; init; }
}

public sealed class Author {
    public Guid AuthorId { get; init; } = default!;
    public Contacts Contacts { get; init; }
}

public sealed class Contacts {
    public Contact PrimaryContact { get; init; } = default!;
    public Contact SecondaryContact { get; init; }
}

public sealed class Contact {
    public string PhoneNumber { get; init; } = default!;
    public string EmailAddress { get; init; } = default!;
}

Stack Trace

System.InvalidOperationException: The object has been removed from the model.
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.get_Builder()
   at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertiesSnapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.Snapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationshipSnapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertiesSnapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.Snapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity& type, ConfigurationSource configurationSource, Nullable`1 shouldBeOwned)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.SharedTypeEntity(String name, Type type, ConfigurationSource configurationSource, Nullable`1 shouldBeOwned)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.MakeDeclaringTypeShared(Nullable`1 configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.GetTargetEntityTypeBuilder(TypeIdentity targetEntityType, MemberIdentity navigation, Nullable`1 configurationSource, Nullable`1 targetShouldBeOwned)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(TypeIdentity& targetEntityType, MemberIdentity& navigation, Nullable`1 inverse, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasOwnership(TypeIdentity& typeIdentity, MemberIdentity navigation, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.OwnsOneBuilder[TRelatedEntity](TypeIdentity ownedType, MemberIdentity navigation)
   at Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.OwnsOne[TRelatedEntity](Expression`1 navigationExpression, Action`1 buildAction)
   at UserQuery.ApplicationContext.<>c.<OnModelCreating>b__9_1(EntityTypeBuilder`1 author), line 41
   at Microsoft.EntityFrameworkCore.ModelBuilder.Entity[TEntity](Action`1 buildAction)
   at UserQuery.ApplicationContext.OnModelCreating(ModelBuilder model), line 40
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__8_4(IServiceProvider p)
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreatedAsync(CancellationToken cancellationToken)
   at UserQuery.Main(), line 16

Provider and version information

Regression: Works in 5.0.12
EF Core version: 6.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer or Microsoft.EntityFrameworkCore.InMemoryDatabase
Target framework: .NET 6.0.100
Operating system: Windows 11
IDE: Visual Studio 2019, Visual Studio 2022, LinqPad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions