如何从DataAnnotations获取StringLength

时间:2015-04-23 13:21:47

标签: c# asp.net-mvc data-annotations

更新建议后,我仍然收到错误

使用FirstOrDefault()StringLength

进行了尝试

enter image description here

我需要检索 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; } } 注释值,这是我的代码,但是我收到以下错误。

我尝试从here实现几乎相同的代码,但收到错误:

  

序列不包含元素

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

//调用:

`id` int(11) NOT NULL, 

5 个答案:

答案 0 :(得分:7)

我能够理解,测试并且工作得很好,万一其他人在寻找!

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

答案 1 :(得分:1)

您可以从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()获得答案。

因此,您需要尝试使用SingleOrDefault()代替Single()

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

答案 2 :(得分:0)

您是否尝试将长度显示为错误消息的一部分?如果是这样,我相信你可以放......

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

答案 3 :(得分:0)

var maxLength = typeof(EmployeeViewModel)
                    .GetProperty("Name")
                    .GetCustomAttributes<StringLengthAttribute>()
                    .FirstOrDefault()
                    .MaximumLength;

答案 4 :(得分:0)

当我刚刚解决这个问题时,我想我会提供我正在玩的LinqPad代码。它足够完整,可以在Linqpad中运行,如果你想探索,只需添加导入。

注意我在哪里评论你真正需要的位。我发现有时候在没有某些背景的情况下调整代码会很棘手。

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