Search code examples
c#asp.netenums

.Net using Enum as data annotation , DTO , and DB column


I'm new to .NET, and I've been struggling with using Enum as data annotation for validation in my requests. It took me a full day to solve most of the issues, but I'm not confident that my solution is good practice.

My goal is to implement validation on a FormBody property where the type of that property is an Enum.

Here's an example of the Enum:

public enum Color
{
    Red,
    Green,
    Blue
}

Now, to simplify the question, I have two models that use this Color. Let's call them Car and CarDtoRequest.

In the CarDtoRequest, which is used as the type for FromBody, it looks like this:

public class CarDtoRequest
{
    [Required]
    [EnumDataType(typeof(Color), ErrorMessage = "Color must be either 'Red', 'Green', or 'Blue'")]
    public string Color { get; set; }
}

Also, the actual Car type class looks like this:

public class Car
{
    [Column(TypeName = "nvarchar(50)")]
    public Color Color { get; set; }
}

My first question is, it took me 3-4 hours, and I still can't assign a dynamic string into the ErrorMessage that joins all the values from the Color (any non-static string shows the error: CS0182: An attribute argument must be a constant expression, typeof expression, or array creation expression of an attribute parameter type).

Additionally, I migrated to the database in the DbContext class as follows:

public DbSet<Car> Cars { get; set; }

The validation works, and it will only work if the FromBody color is one of the enum values. Also, it saves it in the database as a string, but in my code, it still gets saved as a number.

I'm using AutoMapper to convert from the domain model to the DTO model and vice versa.

However, all of this doesn't seem like good practice and professional. Any suggestions for improvement would be appreciated.


Solution

  • Try a custom Get/Set

        public class Car
        {
            private Color c { get; set; }
            public string Color {
                get { return c.ToString(); } 
                set { c = (Color)Enum.Parse(typeof(Color), value); }
            }
        }