简体   繁体   中英

Setting a column unique null without being an index in .NET EF Core

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.

I have encounter this problem before. The reason why this cannot be done with fluent API is most likely (i'm speculating) because several databases doesn't allow this feature, and it makes sense. this post explains why:

MySQL: UNIQUE constraint without index

If you still wanna do this, just run a command on the OnModelCreating like this:

context.Database.ExecuteSqlCommand("ALTER TABLE table
DROP CONSTRAINT table_constraint"); //SQL Server / Oracle / MS Access

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM