简体   繁体   English

在 .NET EF Core 中设置列​​唯一空值而不是索引

[英]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:这对 SQL 是可行的,在 mysql 中是这样的:

CREATE TABLE MyTable (
  ...
  field VARCHAR(255) UNIQUE
  ...
)

I tried overriding DbContext.OnModelCreating and adding these:我尝试覆盖DbContext.OnModelCreating并添加这些:

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'}.下面的代码给了我一条错误消息,指出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.如果有一种方法可以让我手动添加 SQL,我会同意的。 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.如果我手动编辑迁移文件,我不知道这是否可行,但migration.Design.cs文件使用相同的ModelBuilder类,所以我只能使用相同的方法。

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.使用 fluent API 无法做到这一点的原因很可能是(我在推测),因为有几个数据库不允许使用此功能,这是有道理的。 this post explains why:这篇文章解释了原因:

MySQL: UNIQUE constraint without index MySQL:没有索引的唯一约束

If you still wanna do this, just run a command on the OnModelCreating like this:如果您仍然想这样做,只需像这样在 OnModelCreating 上运行命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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