Entity Framework Core add unique constraint code-first

前端 未结 9 997
南方客
南方客 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:14

    None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

    In the instance below I want to ensure the OutletRef field is unique:

    public class ApplicationDbContext : IdentityDbContext
        {
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity()
                    .HasIndex(o => new { o.OutletRef });
            }
        }
    
    

    This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

提交回复
热议问题