Home > Mobile >  How to make enum members unique and not the whole enum in .NET
How to make enum members unique and not the whole enum in .NET

Time:12-02

I have an enum, which is used in a model. I would like to have one entity with each member in the enum field, but not with the enum itself. Is there a way to specify it with annotation or in the DbContext?

The enum:

public enum TagType : short
{
    Rfid,
    CustomText,
}

The model

public class Tag
{
    [Key]
    public long Id { get; set; }

    [Required]
    public string Value { get; set; }
    
    [Required]
    public TagType Discriminator { get; set; }

}

The following 2 entities should be allowed to be created Tag {1, "823", Rfid}, {2, "123", CustomText}, but not Tag {1, "823", Rfid}, {2, "123", Rfid} or Tag {1, "823", CustomText}, {2, "123", CustomText}

CodePudding user response:

You can add the Unique Constraint to have one entity with each member. Change your DbContext like below:

public class MvcProjContext : DbContext
{
    public MvcProjContext (DbContextOptions<MvcProjContext> options)
        : base(options)
    {
    }

    public DbSet<Tag> Tag { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Tag>()
            .HasAlternateKey(r => r.Discriminator);
    }
}
  • Related