Home > Back-end >  How to make out of three property only two can be null in C#
How to make out of three property only two can be null in C#

Time:11-19

I am new to asp.net core web api. I want to make announcement module for my school project. What i want to make is that admins can send announcement based on role or target user or target section. when the request come it must contain at least one not null, How can I achieve this in the class property.


    public class Announcement
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Detail { get; set; }
        public DateTime Date { get; set; }
        public string? Attachment { get; set; }
        public AppUser Poster { get; set; }
        public string PosterUserId { get; set; }
        public AppUser? Receiver { get; set; }
        public string? ReceiverUserId { get; set; }
        public Section? Section { get; set; }
        public int? SectionId { get; set; }
        public IdentityRole? Role { get; set; }
        public string? RoleId { get; set; }
    }

I can achieve this in the controller but, Is there any method I can use so that the model binder will reject it if three of them are null.

CodePudding user response:

Going by the documentation @Rand Random linked. You want to make your class an IValidatableObject and then implement the Validate method. Something like this:

public class Announcement : IValidatableObject
{
...

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (IdentityRole == null && Section == null && Receiver == null)
        {
            yield return new ValidationResult(
                $"You must have at least one field of Role, Target User, or Target Section selected.",
                new[] { nameof(IdentityRole), nameof(Section), nameof(Receiver) });
        }
    }
}

CodePudding user response:

you jut have to declare in your dto class or model class for example

public string Title { get; set; } = string.Empty;
  • Related