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

标签 c# entity-framework entity-framework-4 code-first

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

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

酒吧开发

最佳答案

你总是可以使用反射来检查属性值,尽管如果你能绕过它,这种方法并不是最好的——它并不漂亮:

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

关于C# 如何使用 DataAnnotations StringLength 和 SubString 删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287752/

相关文章:

c# - ECDH Nodejs 和 C# key 交换

c# - 在平局的结果中加 0.5 来反击?

c# - 为什么代码首先要创建索引列?

asp.net-mvc-3 - 未调用 FluentValidation 验证器

visual-studio - 保存 EDMX 时是否可以防止重新生成 T4 文件?

c# - Entity Framework 模型生成奇怪的错误消息

c# - Visual Studio 2010 在崩溃时清空文件

c# - 使用数据源和 Entity Framework 填充以编程方式声明的 datagridview

c# - 使用 Entity Framework 模型插入数据

c# - 如何将 LateX/Math 添加到 Windows 10 Ink API?