efcore
efcore copied to clipboard
ModelBuilder and UseIdentityColumn fails to set identity property on column
Microsoft.EntityFrameworkCore.SqlServer 8.0.4
I'm using ModelBuilder to build a model up front; the ModelBuilder api feels more intuitive than the OnModelCreating approach to me. For my tests I use EnsureCreated to initialize a new database off of the model. I'm facing an issue with properties configured using UseIdentityColumn() where the identity property isn't being set on the column in the new database.
If I switch to use the OnModelCreating approach to setup the model, the identity property is set as expected.
The following code demonstrates the approach that is affected by this issue.
public class TestModel
{
public virtual int Id { get; set; }
public virtual string Code { get; set; } = string.Empty;
}
public class TestModelConfiguration : IEntityTypeConfiguration<TestModel>
{
public void Configure(EntityTypeBuilder<TestModel> builder)
{
builder.ToTable("Test");
builder.HasKey(x => x.Id);
builder
.Property(x => x.Id)
.UseIdentityColumn();
builder
.Property(x => x.Code)
.IsRequired()
.HasMaxLength(70);
}
}
ModelBuilder modelBuilder = new(SqlServerConventionSetBuilder.Build());
modelBuilder.ApplyConfigurationsFromAssembly(typeof(TestModelConfiguration).Assembly);
DbContextOptionsBuilder dbContextOptions = new();
dbContextOptions.UseSqlServer(connectionString);
dbContextOptions.UseModel(modelBuilder.FinalizeModel());
using TestDbContext dbContext = new(_dbContextOptions.Options);
dbContext.Database.EnsureCreated();