I am working on a legacy system using Entity Framework 6.0 and there was a new requirement to allow users to re-use a code that had been used before on a deleted record. To do this I added a nullable DeletedDate column and a unique index that combined the code and deleted date.
To achieve this I added the following code to the OnModelCreating method on the DataContext.
modelBuilder.Entity<MyEntity>().HasIndex(e => new {e.Code, e.DeletedDate}).IsUnique();
This worked well. But then we had a similar requirement where the user wanted to reuse names as well as codes and not necessarily together. So I thought I could just do this:
modelBuilder.Entity<MyEntity>().HasIndex(e => new {e.Name, e.DeletedDate}).IsUnique();
modelBuilder.Entity<MyEntity>().HasIndex(e => new {e.Code, e.DeletedDate}).IsUnique();
This compiles, runs and throws no errors,but when I inspect the resulting indexes on the database, the first one always loses the DeletedDate column from its definition, creating a unique index on Name only. I can add the DeletedDate column back manually in SQL Server but EF simply won't do it for me.
Is this a bug or is there a good reason why I can't do this? Perhaps more importantly, is there a way I can achieve this in EF code first?
We are using SQL Server 2019.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…