Nic*_*dko 144 ef-code-first entity-framework-4.1 asp.net-mvc-3
行为[MaxLength]
和[StringLength]
属性有什么区别?
据我所知(除了[MaxLength]
可以验证数组的最大长度)这些是相同的,有点多余?
Swa*_*aff 195
MaxLength用于实体框架,以决定在创建数据库时创建字符串值字段的大小.
来自MSDN:
指定属性中允许的数组或字符串数据的最大长度.
StringLength是一个数据注释,将用于验证用户输入.
来自MSDN:
指定数据字段中允许的最小和最大字符长度.
小智 41
我刚从另一篇文章中学到的一些快速但非常有用的附加信息,但似乎无法找到文档(如果有人可以在MSDN上共享它的链接那将是惊人的):
与这些属性关联的验证消息实际上将替换与属性关联的占位符.例如:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Run Code Online (Sandbox Code Playgroud)
如果超过字符限制,将输出以下内容: "地址最多可包含100个字符"
我所知道的占位符是:
非常感谢bloudraak最初指出这一点.
gma*_*ser 11
以下是我们使用both [MaxLength]
和[StringLength]
属性时的结果EF code first
.如果两者都使用,[MaxLength]
赢得比赛.请参阅studentname
下面课程中的测试结果
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
需要注意的另一点是在MaxLength属性中,您只能提供最大所需范围而不是最小所需范围。而在StringLength可以提供两种。
小智 5
MaxLengthAttribute 表示最大值。允许的数组或字符串数据的长度
StringLengthAttribute 表示最小值。和最大。数据字段中允许的字符长度
访问http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/