Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot configure different Identity column facets for different tables in TPC mapping #28195

Closed
ajcvickers opened this issue Jun 9, 2022 · 7 comments · Fixed by #28354
Closed
Labels
area-model-building closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-enhancement
Milestone

Comments

@ajcvickers
Copy link
Contributor

Tried to do this for value generation using Identity columns with gaps. Possibly just part of #19811, but we should check that this scenario works.

        modelBuilder.Entity<Animal>().UseTpcMappingStrategy();
        modelBuilder.Entity<Cat>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(1, 3);
        modelBuilder.Entity<Dog>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(2, 3);
        modelBuilder.Entity<FarmAnimal>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(3, 3);

Tables:

      CREATE TABLE [Cats] (
          [Id] int NOT NULL,
          [Species] nvarchar(max) NULL,
          [Name] nvarchar(max) NULL,
          [EdcuationLevel] nvarchar(max) NULL,
          CONSTRAINT [PK_Cats] PRIMARY KEY ([Id])
      );

      CREATE TABLE [Dogs] (
          [Id] int NOT NULL,
          [Species] nvarchar(max) NULL,
          [Name] nvarchar(max) NULL,
          [FavoriteToy] nvarchar(max) NULL,
          CONSTRAINT [PK_Dogs] PRIMARY KEY ([Id])
      );

      CREATE TABLE [FarmAnimals] (
          [Id] int NOT NULL,
          [Species] nvarchar(max) NULL,
          [Value] decimal(18,2) NOT NULL,
          CONSTRAINT [PK_FarmAnimals] PRIMARY KEY ([Id])
      );

Full code:

public abstract class Animal
{
    public int Id { get; set; }
    public string Species { get; set; }
}

public class FarmAnimal : Animal
{
    public decimal Value { get; set; }
}

public abstract class Pet : Animal
{
    public string Name { get; set; }
}

public class Cat : Pet
{
    public string EdcuationLevel { get; set; }
}

public class Dog : Pet
{
    public string FavoriteToy { get; set; }
}


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

    
    public DbSet<Animal> Animals { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Animal>().UseTpcMappingStrategy();
        modelBuilder.Entity<Cat>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(1, 3);
        modelBuilder.Entity<Dog>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(2, 3);
        modelBuilder.Entity<FarmAnimal>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(3, 3);
    }
}

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

            context.AddRange(
                new Cat {Name = "Alice", Species = "Felis catus", EdcuationLevel = "MBA"},
                new Cat {Name = "Mac", Species = "Felis catus", EdcuationLevel = "BA"},
                new Dog {Name = "Toast", Species = "Canis familiaris", FavoriteToy = "Mr. Squirrel"},
                new FarmAnimal {Value = 100.0m, Species = "Ovis aries"});

            context.SaveChanges();
        }
    }
}
@AndriySvyryd
Copy link
Member

Split off from #27970

@ajcvickers ajcvickers added this to the 7.0.0 milestone Jun 15, 2022
AndriySvyryd added a commit that referenced this issue Jun 29, 2022
…ents

Add support for annotations to mapping fragments, property overrides and sequences

Fixes #28195
Fixes #28237
AndriySvyryd added a commit that referenced this issue Jul 1, 2022
…ents

Add support for annotations to mapping fragments, property overrides and sequences
Update back-reference on mapping fragments and overrides when reattaching

Fixes #28195
Fixes #28237
@AndriySvyryd AndriySvyryd removed their assignment Jul 1, 2022
@AndriySvyryd AndriySvyryd added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label Jul 1, 2022
AndriySvyryd added a commit that referenced this issue Jul 1, 2022
Add support for annotations to mapping fragments, property overrides and sequences
Update back-reference on mapping fragments and overrides when reattaching

Fixes #28195
Fixes #28237
@ajcvickers ajcvickers modified the milestones: 7.0.0, 7.0.0-preview7 Jul 7, 2022
@ajcvickers
Copy link
Contributor Author

This still doesn't work.

Exception:

      An exception occurred in the database while saving changes for context type 'AnimalsContext'.
      Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
       ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'AnimalsContext.dbo.Cats'; column does not allow nulls. UPDATE fails.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
         at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
         at Microsoft.Data.SqlClient.SqlDataReader.ReadAsyncExecute(Task task, Object state)
         at Microsoft.Data.SqlClient.SqlDataReader.InvokeAsyncCall[T](SqlDataReaderAsyncCallContext`1 context)
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagationAsync(Int32 startResultSetIndex, RelationalDataReader reader, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
      ClientConnectionId:ccc6aafb-b735-4a95-9ee9-1735cafd8fc6
      Error Number:515,State:2,Class:16
         --- End of inner exception stack trace ---
         at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Unhandled exception. Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'AnimalsContext.dbo.Cats'; column does not allow nulls. UPDATE fails.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
   at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
   at Microsoft.Data.SqlClient.SqlDataReader.ReadAsyncExecute(Task task, Object state)
   at Microsoft.Data.SqlClient.SqlDataReader.InvokeAsyncCall[T](SqlDataReaderAsyncCallContext`1 context)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagationAsync(Int32 startResultSetIndex, RelationalDataReader reader, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
ClientConnectionId:ccc6aafb-b735-4a95-9ee9-1735cafd8fc6
Error Number:515,State:2,Class:16
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in C:\local\code\AllTogetherNow\Inheritance\Program.cs:line 39
   at Program.<Main>(String[] args)

Schema:

      CREATE TABLE [Cats] (
          [Id] int NOT NULL,
          [Name] nvarchar(max) NOT NULL,
          [FoodId] uniqueidentifier NULL,
          [Vet] nvarchar(max) NULL,
          [EducationLevel] nvarchar(max) NOT NULL,
          CONSTRAINT [PK_Cats] PRIMARY KEY ([Id])
      );
      CREATE TABLE [Dogs] (
          [Id] int NOT NULL,
          [Name] nvarchar(max) NOT NULL,
          [FoodId] uniqueidentifier NULL,
          [Vet] nvarchar(max) NULL,
          [FavoriteToy] nvarchar(max) NOT NULL,
          CONSTRAINT [PK_Dogs] PRIMARY KEY ([Id])
      );
      CREATE TABLE [FarmAnimals] (
          [Id] int NOT NULL,
          [Name] nvarchar(max) NOT NULL,
          [FoodId] uniqueidentifier NULL,
          [Value] decimal(18,2) NOT NULL,
          [Species] nvarchar(max) NOT NULL,
          CONSTRAINT [PK_FarmAnimals] PRIMARY KEY ([Id])
      );
      CREATE TABLE [Humans] (
          [Id] int NOT NULL,
          [Name] nvarchar(max) NOT NULL,
          [FoodId] uniqueidentifier NULL,
          [FavoriteAnimalId] int NULL,
          CONSTRAINT [PK_Humans] PRIMARY KEY ([Id])
      );

Code:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using (var context = new AnimalsContext())
{
    await context.Database.EnsureDeletedAsync();

    Console.WriteLine(context.Model.ToDebugString());
    Console.WriteLine();

    await context.Database.EnsureCreatedAsync();

    var catFood = new PetFood("Lily's Kitchen", LifeStage.Adult);
    var dogFood = new PetFood("Canagan", LifeStage.Adult);
    var hay = new FarmFood("Hay");
    var sushi = new HumanFood("Sushi", 670);

    var arthur = new Human("Arthur") { Food = sushi };
    var wendy = new Human("Wendy");
    var christi = new Human("Christi");

    var alice = new Cat("Alice", "MBA") { Vet = "Pengelly", Food = catFood, Humans = { arthur, wendy } };

    var mac = new Cat("Mac", "Preschool") { Vet = "Pengelly", Food = catFood, Humans = { arthur, wendy } };

    var toast = new Dog("Toast", "Mr. Squirrel") { Vet = "Pengelly", Food = dogFood, Humans = { arthur, wendy } };

    var clyde = new FarmAnimal("Clyde", "Equus africanus asinus") { Value = 100.0m, Food = hay };

    wendy.FavoriteAnimal = toast;
    arthur.FavoriteAnimal = alice;
    christi.FavoriteAnimal = clyde;

    await context.AddRangeAsync(wendy, arthur, christi, alice, mac, toast, clyde);
    await context.SaveChangesAsync();
}

Console.WriteLine();

using (var context = new AnimalsContext())
{

    foreach (var human in context.Humans)
    {
        Console.WriteLine($"Human.FavoriteAnimalId = {context.Entry(human).Property("FavoriteAnimalId").CurrentValue}");
    }
}

public abstract class Animal
{
    protected Animal(string name)
    {
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public abstract string Species { get; }

    public Food? Food { get; set; }
}

public abstract class Pet : Animal
{
    protected Pet(string name)
        : base(name)
    {
    }

    public string? Vet { get; set; }

    public ICollection<Human> Humans { get; } = new List<Human>();
}

public class FarmAnimal : Animal
{
    public FarmAnimal(string name, string species)
        : base(name)
    {
        Species = species;
    }

    public override string Species { get; }

    [Precision(18, 2)]
    public decimal Value { get; set; }

    public override string ToString()
        => $"Farm animal '{Name}' ({Species}/{Id}) worth {Value:C} eats {Food?.ToString() ?? "<Unknown>"}";
}

public class Cat : Pet
{
    public Cat(string name, string educationLevel)
        : base(name)
    {
        EducationLevel = educationLevel;
    }

    public string EducationLevel { get; set; }

    public override string Species
        => "Felis catus";

    public override string ToString()
        => $"Cat '{Name}' ({Species}/{Id}) with education '{EducationLevel}' eats {Food?.ToString() ?? "<Unknown>"}";
}

public class Dog : Pet
{
    public Dog(string name, string favoriteToy)
        : base(name)
    {
        FavoriteToy = favoriteToy;
    }

    public string FavoriteToy { get; set; }

    public override string Species
        => "Canis familiaris";

    public override string ToString()
        => $"Dog '{Name}' ({Species}/{Id}) with favorite toy '{FavoriteToy}' eats {Food?.ToString() ?? "<Unknown>"}";
}

public class Human : Animal
{
    public Human(string name)
        : base(name)
    {
    }

    public override string Species
        => "Homo sapiens";

    public Animal? FavoriteAnimal { get; set; }
    public ICollection<Pet> Pets { get; } = new List<Pet>();

    public override string ToString()
        => $"Human '{Name}' ({Species}/{Id}) with favorite animal '{FavoriteAnimal?.Name ?? "<Unknown>"}'"
            + $" eats {Food?.ToString() ?? "<Unknown>"}";
}

public abstract class Food
{
    public Guid Id { get; set; }
}

public class PetFood : Food
{
    public PetFood(string brand, LifeStage lifeStage)
    {
        Brand = brand;
        LifeStage = lifeStage;
    }

    public string Brand { get; set; }
    public LifeStage LifeStage { get; set; }

    public override string ToString()
        => $"Pet food by '{Brand}' ({Id}) for life stage {LifeStage}";
}

public enum LifeStage
{
    Juvenile,
    Adult,
    Senior
}

public class HumanFood : Food
{
    public HumanFood(string name, int calories)
    {
        Name = name;
        Calories = calories;
    }

    [Column("Name")]
    public string Name { get; set; }

    public int Calories { get; set; }

    public override string ToString()
        => $"{Name} ({Id}) with calories {Calories}";
}

public class FarmFood : Food
{
    public FarmFood(string name)
    {
        Name = name;
    }

    [Column("Name")]
    public string Name { get; set; }

    public override string ToString()
        => $"{Name} ({Id})";
}

public class AnimalsContext : DbContext
{
    public DbSet<Animal> Animals
        => Set<Animal>();

    public DbSet<Pet> Pets
        => Set<Pet>();

    public DbSet<FarmAnimal> FarmAnimals
        => Set<FarmAnimal>();

    public DbSet<Cat> Cats
        => Set<Cat>();

    public DbSet<Dog> Dogs
        => Set<Dog>();

    public DbSet<Human> Humans
        => Set<Human>();

    public DbSet<Food> Foods
        => Set<Food>();

    public DbSet<PetFood> PetFoods
        => Set<PetFood>();

    public DbSet<FarmFood> FarmFoods
        => Set<FarmFood>();

    public DbSet<HumanFood> HumanFoods
        => Set<HumanFood>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .EnableSensitiveDataLogging()
            .UseSqlServer(@$"Server=(localdb)\mssqllocaldb;Database={GetType().Name}");

        optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Animal>().UseTpcMappingStrategy();
        modelBuilder.Entity<Cat>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(1, 4);
        modelBuilder.Entity<Dog>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(2, 4);
        modelBuilder.Entity<FarmAnimal>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(3, 4);
        modelBuilder.Entity<Human>().Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(4, 4);
        
        modelBuilder.Entity<Food>().UseTpcMappingStrategy();

        modelBuilder.Entity<FarmAnimal>().Property(e => e.Species);

        modelBuilder.Entity<Human>()
            .HasMany(e => e.Pets)
            .WithMany(e => e.Humans)
            .UsingEntity<Dictionary<object, string>>(
                "PetsHumans",
                r => r.HasOne<Pet>().WithMany().OnDelete(DeleteBehavior.Cascade),
                l => l.HasOne<Human>().WithMany().OnDelete(DeleteBehavior.ClientCascade));
    }
}

@ajcvickers ajcvickers reopened this Aug 12, 2022
@ajcvickers ajcvickers removed this from the 7.0.0-preview7 milestone Aug 12, 2022
@AndriySvyryd
Copy link
Member

		modelBuilder.Entity<Cat>().ToTable(tb => tb.Property(e => e.Id).UseIdentityColumn(1, 4));
		modelBuilder.Entity<Dog>().ToTable(tb => tb.Property(e => e.Id).UseIdentityColumn(2, 4));
		modelBuilder.Entity<FarmAnimal>().ToTable(tb => tb.Property(e => e.Id).UseIdentityColumn(3, 4));
		modelBuilder.Entity<Human>().ToTable(tb => tb.Property(e => e.Id).UseIdentityColumn(4, 4));

@AndriySvyryd AndriySvyryd added this to the 7.0.0-preview7 milestone Aug 13, 2022
@ajcvickers
Copy link
Contributor Author

Unhandled exception. System.InvalidOperationException: Table name must be specified to configure a table-specific property mapping.
   at Microsoft.EntityFrameworkCore.Metadata.Builders.TableBuilder.GetStoreObjectIdentifier()
   at Microsoft.EntityFrameworkCore.Metadata.Builders.TableBuilder`1.Property[TProperty](Expression`1 propertyExpression)
   at AnimalsContext.<>c.<OnModelCreating>b__21_0(TableBuilder`1 tb) in C:\local\code\AllTogetherNow\Inheritance\Program.cs:line 331
   at Microsoft.EntityFrameworkCore.RelationalEntityTypeBuilderExtensions.ToTable[TEntity](EntityTypeBuilder`1 entityTypeBuilder, Action`1 buildAction)
   at AnimalsContext.OnModelCreating(ModelBuilder modelBuilder) in C:\local\code\AllTogetherNow\Inheritance\Program.cs:line 331
   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 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   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.EnsureDeletedAsync(CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in C:\local\code\AllTogetherNow\Inheritance\Program.cs:line 10
   at Program.<Main>(String[] args)

Process finished with exit code -532,462,766.

@ajcvickers ajcvickers removed this from the 7.0.0-preview7 milestone Aug 14, 2022
@ajcvickers ajcvickers reopened this Aug 14, 2022
@ajcvickers
Copy link
Contributor Author

Adding table names to the configuration gets us back to the original exception:

        modelBuilder.Entity<Cat>().ToTable("Cats", tb => tb.Property(e => e.Id).UseIdentityColumn(1, 4));
        modelBuilder.Entity<Dog>().ToTable("Dogs", tb => tb.Property(e => e.Id).UseIdentityColumn(2, 4));
        modelBuilder.Entity<FarmAnimal>().ToTable("FarmAnimals", tb => tb.Property(e => e.Id).UseIdentityColumn(3, 4));
        modelBuilder.Entity<Human>().ToTable("Humans", tb => tb.Property(e => e.Id).UseIdentityColumn(4, 4));

@ajcvickers ajcvickers added this to the 7.0.0-rc1 milestone Aug 16, 2022
@ajcvickers ajcvickers removed this from the 7.0.0-rc1 milestone Nov 5, 2022
@ajcvickers ajcvickers added this to the 7.0.0 milestone Nov 5, 2022
@AndriySvyryd AndriySvyryd removed their assignment Oct 9, 2023
@GermanOller2001
Copy link

Hey, @ajcvickers any news on this? I run into the same problem.

@AndriySvyryd
Copy link
Member

@GermanOller2001 This has been fixed in EF 7.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-model-building closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-enhancement
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants