Home > OS >  How to get max length of a property using Entity Framework Core
How to get max length of a property using Entity Framework Core

Time:01-20

I have an entity where I have few string properties. I have set the MaxLength for them in my model class. Now I want to get the max length of each field. How can I achieve it?

public class Customer
{
        [Key]
        public int CustId { get; set; }

        [MaxLength(100)]
        public string Cust { get; set; }

        [MaxLength(100)]
        public string Street { get; set; }

        [MaxLength(20)]
        public string PostalCode { get; set; }

        [MaxLength(100)]
        public string City { get; set; }

        [MaxLength(2)]
        public string Country { get; set; }
}

CodePudding user response:

You can use reflection to get the max length of each field. Here's an example of how you can do this in C#:

class MyModel {
    [MaxLength(50)]
    public string Field1 { get; set; }
    [MaxLength(100)]
    public string Field2 { get; set; }
    [MaxLength(200)]
    public string Field3 { get; set; }
}

class Program {
    static void Main(string[] args) {
        var modelType = typeof(MyModel);
        var properties = modelType.GetProperties();
        foreach (var property in properties) {
            var maxLengthAttribute = property.GetCustomAttribute<MaxLengthAttribute>();
            if (maxLengthAttribute != null) {
                Console.WriteLine($"{property.Name}: {maxLengthAttribute.Length}");
            }
        }
    }
}

This will output:

Field1: 50
Field2: 100
Field3: 200
  • Related