The first EF6 Code key is not automatically incremented

I have this cool model:

public class Results
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int GameId { get; set; }
    public Games Game { get; set; }
    public string Notes { get; set; }
    public virtual ICollection<ResultItems> ResultItems { get; set; }
}

      

For some reason, the Id field doesn't get auto increment according to the schema:

CREATE TABLE [dbo].[Results] 
(
    [Id]     INT            NOT NULL,
    [GameId] INT            NOT NULL,
    [Notes]  NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_dbo.Results] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.Results_dbo.Games_GameId] 
        FOREIGN KEY ([GameId]) REFERENCES [dbo].[Games] ([Id]) ON DELETE CASCADE
);
GO

CREATE NONCLUSTERED INDEX [IX_GameId] ON [dbo].[Results]([GameId] ASC);

      

I also added:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Results>().HasKey(p => p.Id).Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        base.OnModelCreating(modelBuilder);
}

      

into my db context, but still the migration doesn't automatically increment this field. Can anyone see where I am doing something wrong?

Thank.

Paul.

+3


source to share


1 answer


Sql server does not support alter column to add authentication functionality. while your table is created and you don't want to lose your data, you cannot do that automatically, back up the table, drop the column (ignore in EF) and recreate the table or column with EF, abd restore your values



+5


source







All Articles