C#如何使用DataAnnotations StringLength和SubString删除文本
我有一个模型类,它有一个description属性,数据注释属性为StringLength,长度设置为100个字符。当这个属性超过100个字符并且Entity Framework试图保存这个属性时,我会得到以下错误C#如何使用DataAnnotations StringLength和SubString删除文本,c#,entity-framework,entity-framework-4,code-first,C#,Entity Framework,Entity Framework 4,Code First,我有一个模型类,它有一个description属性,数据注释属性为StringLength,长度设置为100个字符。当这个属性超过100个字符并且Entity Framework试图保存这个属性时,我会得到以下错误 [StringLength(100, ErrorMessage = "Description Max Length is 100")] public string Description { get; set; } 错误: “一个或多个实体的验证失败。有关详细信息
[StringLength(100, ErrorMessage = "Description Max Length is 100")]
public string Description { get; set; }
错误:“一个或多个实体的验证失败。有关详细信息,请参阅'EntityValidationErrors'属性” 我不确定这是否有助于形成解决方案,但我首先使用实体框架CTP5和代码 我想做的是,如果描述超过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);
创建一个没有长度数据注释的视图模型,然后可以将其映射到实体模型,如果长度超过100,则截断该值。为什么这么麻烦?为什么不呢
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
}
我应该为这个问题添加其他标签吗?我不太了解DataAnnotation。至于其他选项,您可以实现getter/setter,并在setter中执行检查/截断。谢谢您的建议。我只是把它当作一种工作。我可能把问题复杂化了。但是,我可以看到我希望进行验证的不同情况,以及我希望删除额外字符的其他情况。在我的WCF应用程序中,我希望删除多余的字符,而不是引发错误,但在数据输入应用程序(如ASP.NET或Win Forms)中,我希望触发一条验证消息给用户。好的解决方案,我不认为返回可空值有什么意义。默认值为零,因此如果未设置DataAnnotation,您也可以只返回Int zero。我应该提到,我需要在MVC3应用程序中使用数据批注进行有效性验证,这样我就不必重复代码。这完全取决于您希望在何处实施约束。我倾向于保持我的“数据”模型干净,并强制ViewModel进行验证,以便我的ViewModel具有注释。我可以封装它并从代码的任何部分调用它。我要再等一会儿,看看是否能得到更多的答案。谢谢你的回答。你的
集合
完全破坏了验证,只是悄悄地截断了。那是荒谬的。验证或截断。但是无声地截断是一个可怕的想法。