首页 > 解决方案 > 具有唯一约束的实体框架核心版本 5 问题

问题描述

我在 EF Core 5 (5.0.11) 中遇到了唯一约束的问题。

我创建了一个OnModelCreating方法UserContext

    public UserContext(DbContextOptions<UserContext> options) :base(options)
    {
    }

    public DbSet<User> users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasIndex(b => b.Email)
            .IsUnique();
    }

和或在模型中

[Index(nameof(Email), IsUnique = true)]
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

但是如果我运行迁移,我只有这个(没有唯一约束)

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "users",
            columns: table => new
            {
                Id = table.Column<int>(type: "int", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
                Email = table.Column<string>(type: "nvarchar(max)", nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_users", x => x.Id);
            });
    }

标签: asp.net-coreentity-framework-coreentity-framework-migrations

解决方案


推荐阅读