summaryrefslogtreecommitdiff
path: root/Validations/UniqueTier.cs
blob: c91db1ce513d39b93c3dc2fb9eaedaee44b8b3c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.ComponentModel.DataAnnotations;
using BackendPIA.Models;
using BackendPIA.Forms;

namespace BackendPIA.Validations {
    public class UniqueTier : ValidationAttribute {
        public string GetErrorMessage(object? value) {
          return $"The given raffle already has a {value}-Tier.";
        }

        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) {
            var prize = (PrizeForm) validationContext.ObjectInstance;
            var db_context = (ApplicationDbContext) validationContext.GetService(typeof(ApplicationDbContext));

            if(db_context.Prizes.Where(p => p.RaffleId == prize.RaffleId).Where(p => p.Tier == (int) value).Any()) 
                return new ValidationResult(GetErrorMessage(value));
            
            return ValidationResult.Success;
        }
    }
}