Skip to content
New issue

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

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

Already on GitHub? # to your account

Support 64-bit Identity seed values #24840

Closed
josephmoresena opened this issue May 4, 2021 · 7 comments · Fixed by #25030
Closed

Support 64-bit Identity seed values #24840

josephmoresena opened this issue May 4, 2021 · 7 comments · Fixed by #25030
Labels
area-model-building area-sqlserver closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported type-enhancement
Milestone

Comments

@josephmoresena
Copy link

josephmoresena commented May 4, 2021

I'm trying to create a project with Code First with this entity:

[Table(nameof(SQLTable), Schema = "SQLSchema")]
public class SQLTable
{
	[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
	public Int64 Id { get; set; }
	.
	.
	.
}

I want to create an identity for that property with Int64.MinValue as seed. In OnModelCreating method im trying to set that value:

modelBuilder.Entity<SQLTable>().Metadata.SetOrRemoveAnnotation("SqlServer:IdentitySeed", Int64.MinValue.ToString());

But when i'm building migration I getting the following error:

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Nullable`1[System.Int32]'.
   at Microsoft.EntityFrameworkCore.SqlServerPropertyExtensions.GetIdentitySeed(IProperty property, StoreObjectIdentifier& storeObject)
   at Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal.SqlServerAnnotationProvider.For(IColumn column)+MoveNext()
   at Microsoft.EntityFrameworkCore.MutableAnnotatableExtensions.AddAnnotations(IMutableAnnotatable annotatable, IEnumerable`1 annotations)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalModel.Add(IConventionModel model, IRelationalAnnotationProvider relationalAnnotationProvider)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationalModelConvention.ProcessModelFinalized(IModel model)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IModel model)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IModel model)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
   at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(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 singletonCallSite, 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 singletonCallSite, 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__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.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_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.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextT   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to cast object of type 'System.String' to type 'System.Nullable`1[System.Int32]'.

EF Core version: 5.0.5
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: NET 5.0
Operating system:
IDE: Visual Studio 2019 16.9.4

@roji
Copy link
Member

roji commented May 5, 2021

@josephmoresena please try configuring the identity seed as explained in the docs, with UseIdentityColumn. Avoid manipulating metadata directly as you're doing above - that's usually not needed.

@roji roji added the closed-no-further-action The issue is closed and no further action is planned. label May 5, 2021
@josephmoresena
Copy link
Author

@josephmoresena please try configuring the identity seed as explained in the docs, with UseIdentityColumn. Avoid manipulating metadata directly as you're doing above - that's usually not needed.

UseIdentityColumn only admits Int32 input parameters.

@roji roji removed the closed-no-further-action The issue is closed and no further action is planned. label May 5, 2021
@roji
Copy link
Member

roji commented May 5, 2021

Ah, I see now - you're right; this doesn't look like it's possible at the moment without lots of hacking around. You should be able to work around this by altering the identity seed by using raw SQL in your migrations (as demonstrated here).

@ajcvickers ajcvickers changed the title Trying to use Int64 as value for SqlServer:IdentitySeed. Support 64-bit Identity seed values May 10, 2021
@ajcvickers ajcvickers added this to the 6.0.0 milestone May 10, 2021
AndriySvyryd added a commit that referenced this issue Jun 3, 2021
@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 Jun 3, 2021
@AndriySvyryd AndriySvyryd removed their assignment Jun 3, 2021
AndriySvyryd added a commit that referenced this issue Jun 3, 2021
AndriySvyryd added a commit that referenced this issue Jun 4, 2021
@AndriySvyryd AndriySvyryd modified the milestones: 6.0.0, 6.0.0-preview6 Jul 2, 2021
@schuettecarsten
Copy link

When using "Add-Migration" in Package Manager Console, I still get an exception:

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Nullable`1[System.Int64]'.
   at Microsoft.EntityFrameworkCore.SqlServerPropertyExtensions.GetIdentitySeed(IReadOnlyProperty property, StoreObjectIdentifier& storeObject) in Microsoft.EntityFrameworkCore.SqlServer.dll:token 0x6000160+0x22
   at Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal.SqlServerAnnotationProvider.For(IColumn column, Boolean designTime)+MoveNext() in Microsoft.EntityFrameworkCore.SqlServer.dll:token 0x6000494+0xe3
   at Microsoft.EntityFrameworkCore.Infrastructure.AnnotatableBase.AddAnnotations(AnnotatableBase annotatable, IEnumerable`1 annotations) in Microsoft.EntityFrameworkCore.dll:token 0x6001a0f+0x23
[...]

@roji
Copy link
Member

roji commented Aug 19, 2021

@schuettecarsten the code below works for me with EF 6.0.0-preview.7.21378.4, producing the following CREATE TABLE:

CREATE TABLE [Blogs] (
    [Id] bigint NOT NULL IDENTITY(9223372036854775807, 1),
    [Name] nvarchar(max) NULL,
    CONSTRAINT [PK_Blogs] PRIMARY KEY ([Id])
);

Doing the same via migrations works as well. Double-check that you're using the latest preview, and if the problem persists, please open a new issue with a minimal code sample.

Attempted repro
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>().Property(b => b.Id).UseIdentityColumn(long.MaxValue);
    }
}

public class Blog
{
    public long Id { get; set; }
    public string Name { get; set; }
}

@schuettecarsten
Copy link

Okay, this was caused by my existing migrations. I had to replace all .HasAnnotation("SqlServer:IdentitySeed", 1) with .HasAnnotation("SqlServer:IdentitySeed", 1L). It would be great if efcore could handle existing migrations from previous versions.

@ajcvickers
Copy link
Contributor

Thanks @schuettecarsten. I filed #25589 to track this.

@ajcvickers ajcvickers modified the milestones: 6.0.0-preview6, 6.0.0 Nov 8, 2021
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
area-model-building area-sqlserver closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported type-enhancement
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants