简体   繁体   English

如何从DataAnnotations获取StringLength

[英]How to get the StringLength from DataAnnotations

After updating the suggestion I'm still getting the error 更新建议后,我仍然收到错误

Tried both with .SingleOrDefault() or FirstOrDefault() 尝试使用.SingleOrDefault()FirstOrDefault()

在此输入图像描述

I need to retrieve the StringLength annotation value and here is my code but I'm getting the following error. 我需要检索StringLength注释值,这是我的代码,但我收到以下错误。

I have tried to implement pretty much the same code from here but getting the error: 我试图从这里实现几乎相同的代码,但得到错误:

Sequence contains no elements 序列不包含任何元素

    public static class DataAnnotation
    {
        public static int GetMaxLengthFromStringLengthAttribute(Type modelClass, string propertyName)
        {
            int maxLength = 0;
            var attribute = modelClass.GetProperties()
                            .Where(p => p.Name == propertyName)
                            .Single()
                            .GetCustomAttributes(typeof(StringLengthAttribute), true)
                            .Single() as StringLengthAttribute;

            if (attribute != null)
                maxLength = attribute.MaximumLength;

            return 0;
        }
    }

//calling: //调用:

int length = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(EmployeeViewModel), "Name");


public class EmployeeViewModel
{         
    [StringLength(20, ErrorMessage = "Name cannot be longer than 20 characters.")] 
    public string Name{ get; set; }
}

I able to figured out, tested and its working great, in case if anybody else is looking! 我能够想出来,经过测试并且工作得很好,万一其他人在寻找!

  StringLengthAttribute strLenAttr = typeof(EmployeeViewModel).GetProperty(name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().SingleOrDefault();
  if (strLenAttr != null)
  {
     int maxLen = strLenAttr.MaximumLength;
  }

You can get the answer from When you get theLINQ Error “Sequence contains no elements”, this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() . 你可以从当你得到LINQ错误“序列不包含元素”时得到答案,这通常是因为你使用的是First()或Single()命令而不是FirstOrDefault()和SingleOrDefault()

So you need to try using SingleOrDefault() instead of Single() like 所以你需要尝试使用SingleOrDefault()而不是Single()类的

var attribute = modelClass.GetProperties()
                            .Where(p => p.Name == propertyName)
                            .SingleOrDefault()
                            .GetCustomAttributes(typeof(StringLengthAttribute), true)
                            .SingleOrDefault() as StringLengthAttribute;

Are you trying to show length as part of the error message? 您是否尝试将长度显示为错误消息的一部分? If so I believe you can just put... 如果是这样我相信你可以放......

public class EmployeeViewModel
{         
    [StringLength(20, ErrorMessage = "{0} cannot be longer than {1} characters.")] 
    public string Name{ get; set; }
}
var maxLength = typeof(EmployeeViewModel)
                    .GetProperty("Name")
                    .GetCustomAttributes<StringLengthAttribute>()
                    .FirstOrDefault()
                    .MaximumLength;

As I was just tackling this, I thought I'd provide the LinqPad code I'm playing around with. 正如我刚刚解决这个问题,我想我会提供我正在玩的LinqPad代码。 It is complete enough to run in Linqpad, just add the imports if you want to explore. 它足够完整,可以在Linqpad中运行,如果你想探索,只需添加导入。

Note where I comment the bit you actually need. 注意我在哪里评论你实际需要的位。 I've found it tricky sometimes to adapt code without some context. 我发现有时候在没有上下文的情况下调整代码会很棘手。

///The rest of the code given as context as I'm working on a T4 template to create Model classes from Datalayer classes, so the iteration is required in my case
void Main()
{
    CVH p = new CVH();
    Type t = p.GetType();

    foreach (PropertyInfo prop in t.GetProperties()) //Iterating through properties
    {
        foreach (var facet in prop.GetCustomAttributes()) //Yank out attributes
        {
        //The bit you need
            if ((Type)facet.TypeId == typeof(StringLengthAttribute)) //What type of attribute is this? 
            {
                StringLengthAttribute _len = (StringLengthAttribute)facet; //Cast it to grab Maximum/MinimumLengths etc.
                Console.WriteLine($"My maximum field length is { _len.MaximumLength}");
                //End of the bit you need
                Console.WriteLine(_len.MinimumLength);              
            }
        }
    }
}
///Test class with some attributes
public class CVH
{
    [StringLength(50)]
    [DataType(DataType.PhoneNumber)]
    public string phone_1 { get; set; }
    [Required(ErrorMessage = "id is required")]
    public int id { get; set; }
    [Required(ErrorMessage = "id is required")]
    public int contact_id { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EditorFor 和 StringLength 数据注释 - EditorFor and StringLength DataAnnotations C#如何使用DataAnnotations StringLength和SubString删除文本 - C# How to use DataAnnotations StringLength and SubString to remove text string[] 或 List 的 DataAnnotations MaxLength 和 StringLength<string> ? - DataAnnotations MaxLength and StringLength for string[] or List<string>? 如何从不属于模型的类的DataAnnotations中获取HTML注释? - How to get HTML annotations from DataAnnotations from a class that is not part of a model? 获取模型类型和StringLength属性 - Get model type and StringLength attribute 获取StringLength值的扩展方法 - Extension method to get StringLength value 如何获得DataAnnotations.Compare来比较2个不同对象的属性? - How can I get DataAnnotations.Compare to compare properties from 2 different objects? System.ComponentModel.DataAnnotations 属性无法识别。 无法使用 StringLength 属性验证空字符串 - System.ComponentModel.DataAnnotations attribute not recognized. Unable to use StringLength attibute to verify empty string 我可以在 DataAnnotations.StringLength 中使用数字以外的其他属性参数吗? - Can I use other attribute arguments than numbers in DataAnnotations.StringLength? 来自类的DataAnnotations验证 - DataAnnotations validation from a class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM