【译】第15节---数据注解-StringLength

原文:http://www.entityframeworktutorial.net/code-first/stringlength-dataannotations-attribute-in-code-first.aspx

StringLength属性可以应用于类的字符串类型属性。 EF Code First将设置StringLength属性中指定的列的大小。 请注意,它也可以与ASP.Net MVC一起用作验证属性。

请看以下示例:

using System.ComponentModel.DataAnnotations;

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
     
    [StringLength(50)]
    public string StudentName { get; set; }
        
}

如上面的代码所示,我们已经将StringLength属性应用于StudentName。 所以,Code-First将在Student表中创建一个nvarchar(50)列StudentName,如下所示:

如果设置的值大于指定的大小,则EF还会验证StringLength属性的属性值。

例如,如果您设置了超过50个字符长StudentName,则EF将抛出EntityValidationError。

关于StringLength和MaxLength的区别,请移步:https://stackoverflow.com/questions/5717033/stringlength-vs-maxlength-attributes-asp-net-mvc-with-entity-framework-ef-code-f

原文地址:https://www.cnblogs.com/talentzemin/p/7216731.html