简体   繁体   English

C#如何使用DataAnnotations StringLength和SubString删除文本

[英]C# How to use DataAnnotations StringLength and SubString to remove text

I have a model classes that has a description property with a data annotation attribute of StringLength and length is set to 100 characters. 我有一个模型类,它有一个描述属性,数据注释属性为StringLength,长度设置为100个字符。 When this property is more than 100 characters and Entity Framework tries to save this property I get the following error. 当此属性超过100个字符并且实体框架尝试保存此属性时,我收到以下错误。

 [StringLength(100, ErrorMessage = "Description Max Length is 100")]
        public string Description { get; set; }

Error: 错误:
"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details" “一个或多个实体的验证失败。有关详细信息,请参阅'EntityValidationErrors'属性”

I'm not sure if this helps in forming a solution, but I'm using Entity Framework CTP5 and Code First. 我不确定这是否有助于形成解决方案,但我正在使用Entity Framework CTP5和Code First。

What I want to do, is if description is more than 100 characters, then remove characters that are more than 100 characters so that description can be stored and no error will be raised. 我想要做的是,如果描述超过100个字符,然后删除超过100个字符的字符,以便可以存储描述并且不会引发错误。

I believe I should be able to use the DataAnnotation attribute StringLength manually to help me identify the valid length of description and then use SubString to remove any characters over the valid amount. 我相信我应该能够手动使用DataAnnotation属性StringLength来帮助我识别有效的描述长度,然后使用SubString删除有效数量上的任何字符。

Does anyone know how to use DataAnnotation in this situation? 有谁知道在这种情况下如何使用DataAnnotation? Or is there another options that is available? 或者还有其他选择吗?


Update I did what BrokenGlass suggested and here my implementation if: 更新我做了BrokenGlass建议的内容,在这里我的实现如果:

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

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

        return maxLength;
    }
}


int? maxLength = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(Car), "Description");

if(maxLength != null && car.Description.Length > maxLength)
    car.Description = car.Description.Substring(0, maxLength.Value);

BarDev BarDev

You could always check the attribute value using reflection, though that approach is not the best if you can get around it - it's not pretty: 您总是可以使用反射检查属性值,但如果您可以绕过它,那么这种方法并不是最好的 - 它并不漂亮:

var attribute = typeof(ModelClass).GetProperties()
                                  .Where(p => p.Name == "Description")
                                  .Single()
                                  .GetCustomAttributes(typeof(StringLengthAttribute), true) 
                                  .Single() as StringLengthAttribute;

Console.WriteLine("Maximum Length: {0}", attribute.MaximumLength);    

Why all the hassle? 为什么所有的麻烦? Why not 为什么不

private string _description = string.Empty;

[StringLength(100, ErrorMessage = "Description Max Length is 100")]
public string Description 
{  
    get { return _description; }
    set { _description = value.Substring(0,100); };  // or something equivalent
} 

创建一个没有长度数据注释的视图模型,然后可以将其映射到实体模型,并在值超过100时截断该值。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM