Reputation: 560
I have this class 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 does not get set to auto increment as per 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've 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);
}
to my db context but still the migrations do not make this field auto increment. Can anyone see where I'm doing something wrong?
Thanks.
Paul.
Upvotes: 4
Views: 4673
Reputation: 851
sql server does not support alter column for add identity feature. while your table are created , and you don't want loss your data , you cant do it automaticly, back up your table,drop the column(ignore in EF), and recreate your table or column with EF, abd restore your values
Upvotes: 5