Entity Framework Core add unique constraint code-first

前端 未结 9 1008
南方客
南方客 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: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; }
    }
    

提交回复
热议问题