Entity Framework Core add unique constraint code-first

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

    For someone who is trying all these solution but not working try this one, it worked for me

    protected override void OnModelCreating(ModelBuilder builder)
    {
    
        builder.Entity<User>().Property(t => t.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
    
    }
    
    0 讨论(0)
  • 2020-12-12 18:28

    The OP is asking about whether it is possible to add an Attribute to an Entity class for a Unique Key. The short answer is that it IS possible, but not an out-of-the-box feature from the EF Core Team. If you'd like to use an Attribute to add Unique Keys to your Entity Framework Core entity classes, you can do what I've posted here

    public class Company
    {
        [Required]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid CompanyId { get; set; }
    
        [Required]
        [UniqueKey(groupId: "1", order: 0)]
        [StringLength(100, MinimumLength = 1)]
        public string CompanyName { get; set; }
    
        [Required]
        [UniqueKey(groupId: "1", order: 1)]
        [StringLength(100, MinimumLength = 1)]
        public string CompanyLocation { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-12 18:32

    To use it in EF core via model configuration

    public class ApplicationCompanyConfiguration : IEntityTypeConfiguration<Company>
    {
        public void Configure(EntityTypeBuilder<Company> builder)
        {
            builder.ToTable("Company"); 
            builder.HasIndex(p => p.Name).IsUnique();
        }
    }
    
    0 讨论(0)
提交回复
热议问题