StringLength vs MaxLength使用实体框架EF代码优先的属性将ASP.NET MVC

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

[MaxLength][StringLength]属性在行为上有什么区别?

据我所知(除了[MaxLength]可以验证数组的最大长度),它们是相同的并且有些多余吗?


MaxLength用于实体框架,以决定创建数据库时将字符串值字段设置为多大。

从MSDN:

Specifies the maximum length of array
or string data allowed in a property.

StringLength是一个数据批注,将用于验证用户输入。

从MSDN:

Specifies the minimum and maximum
length of characters that are allowed
in a data field.


我刚刚从另一篇文章中学到了一些快速但极其有用的附加信息,但似乎找不到该文档的文档(如果有人可以在MSDN上共享指向它的链接,那将是惊人的):

与这些属性关联的验证消息实际上将替换与属性关联的占位符。例如:

1
2
[MaxLength(100,"{0} can have a max of {1} characters")]
public string Address { get; set; }

如果超出字符数限制,将输出以下内容:
"地址最多可以包含100个字符"

我知道的占位符是:

  • {0} =属性名称
  • {1} =最大长度
  • {2} =最小长度

非常感谢bloudraak最初指出了这一点。


以下是在EF code first中同时使用[MaxLength][StringLength]属性时的结果。如果两者都使用,[MaxLength]将赢得比赛。请参阅下面课程的studentname列中的测试结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 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; }
 }

所有好的答案...从验证的角度来看,我还注意到MaxLength仅在服务器端进行验证,而StringLength也在客户端进行验证。


MaxLengthAttribute表示最大允许的数组或字符串数??据的长度

StringLengthAttribute表示最小值。和最大数据字段中允许的字符长度

访问http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/


需要注意的另一点是,在MaxLength属性中,您只能提供最大所需范围,而不能提供最小所需范围。
在StringLength中,您可以同时提供两者。


我通过在上下文中添加以下行来解决此问题:

1
modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

不知何故,[MaxLength]对我不起作用。


当使用该属性限制网页上表单中文本的最大输入长度时,StringLength似乎会生成maxlength html属性(至少在我的MVC 5测试中)。然后选择一个,然后根据您要如何提醒用户这是最大文本长度来决定。使用stringlength属性,用户将无法键入超出允许长度的值。 maxlength属性不添加此html属性,而是生成数据验证属性,这意味着用户可以键入超出指定的长度,并且防止较长的输入取决于当他移至下一个字段或单击Submit(或如果禁用了javascript,则进行服务器端验证)。在这种情况下,可以通过错误消息通知用户限制。