【问题标题】:How to get max length of a property using Entity Framework Core如何使用 entityframeworkcore 获取属性的最大长度
【发布时间】:2023-01-20 14:43:29
【问题描述】:

我有一个实体,其中几乎没有字符串属性。我在我的模型类中为他们设置了MaxLength。现在我想获得每个字段的最大长度。我怎样才能实现它?

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

【问题讨论】:

  • 目前尚不清楚您希望如何获得最大长度。你能详细说明或举个例子吗?
  • 您可以通过多种方式访问​​信息,但这取决于您希望在何时何地访问它。

标签: c# .net-core entity-framework-core


【解决方案1】:

您可以使用反射来获取每个字段的最大长度。以下是如何在 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}");
            }
        }
    }
}

这将输出:

Field1: 50
Field2: 100
Field3: 200

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2011-02-14
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多