繁体   English   中英

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

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

我有一个模型类,它有一个描述属性,数据注释属性为StringLength,长度设置为100个字符。 当此属性超过100个字符并且实体框架尝试保存此属性时,我收到以下错误。

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

错误:
“一个或多个实体的验证失败。有关详细信息,请参阅'EntityValidationErrors'属性”

我不确定这是否有助于形成解决方案,但我正在使用Entity Framework CTP5和Code First。

我想要做的是,如果描述超过100个字符,然后删除超过100个字符的字符,以便可以存储描述并且不会引发错误。

我相信我应该能够手动使用DataAnnotation属性StringLength来帮助我识别有效的描述长度,然后使用SubString删除有效数量上的任何字符。

有谁知道在这种情况下如何使用DataAnnotation? 或者还有其他选择吗?


更新我做了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

您总是可以使用反射检查属性值,但如果您可以绕过它,那么这种方法并不是最好的 - 它并不漂亮:

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

为什么所有的麻烦? 为什么不

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