Entity Framework Core add unique constraint code-first

前端 未结 9 994
南方客
南方客 2020-12-12 17:36

I can\'t find way to add a unique constraint to my field with using attribute:

public class User
{
    [Required]
    public int Id { get; set; }

    [Requi         


        
9条回答
  •  鱼传尺愫
    2020-12-12 18:20

    Ef core support unique configuration.

    protected override void OnModelCreating(ModelBuilder builder)
    {
      builder.Entity()
        .HasIndex(account => account.Email)
          .IsUnique();
    }
    

    Ef core support multiple unique keys

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity()
          .HasKey(account => new { account.Id, account.Email, account.RoleId });
    }
    

    Don't forget run ef core command to make migration and update the database

    >> dotnet ef migrations add MigrationName -c YourDbContextName
    >> dotnet ef database update -c YourDbContextName
    

提交回复
热议问题