Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get max length of a property using entityframeworkcore

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; }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading