After updating the suggestion I'm still getting the error
Tried both with .SingleOrDefault()
or FirstOrDefault()
I need to retrieve the StringLength
annotation value and here is my code but I'm getting the following error.
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; }
}
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
"Data Annotation provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls." Why would I use Data Annotation? There are 3 main areas where you may use it; two of them are related to your data presentation to your end user and one is to design your database.
DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.
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().
So you need to try using SingleOrDefault()
instead of Single()
like
var attribute = modelClass.GetProperties()
.Where(p => p.Name == propertyName)
.SingleOrDefault()
.GetCustomAttributes(typeof(StringLengthAttribute), true)
.SingleOrDefault() as StringLengthAttribute;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With