I would like to add a field to a table that should be unique, but is not required (so it can be null) and it is not an index. This is doable with SQL, something like this in mysql:
CREATE TABLE MyTable (
...
field VARCHAR(255) UNIQUE
...
)
I tried overriding DbContext.OnModelCreating
and adding these:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// this creates an index, which I don't need/want for this field
modelBuilder.Entity<User>()
.HasIndex(x => x.Field)
.IsUnique();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// This creates a NOT NULL Constraint
modelBuilder.Entity<User>()
.HasAlternateKey(x => x.Field);
}
Thes code below gives me an error message saying The property 'Field' on entity type 'User' cannot be marked as nullable/optional because it has been included in a key {'Field'}.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// This gives me an error
modelBuilder.Entity<User>()
.HasAlternateKey(x => x.Field);
modelBuilder.Entity<User>()
.Property(x => x.Field)
.IsRequired(false);
}
If there is a way for me to just add the SQL by hand, I would be ok with that. I don't know if that is possible if I edit the migration file by hand, but the migration.Design.cs
files use the same ModelBuilder
class, so I only have those same methods to work with.