limit string length entity framework in csharp

To limit the maximum length of a string property in your Entity Framework model, you can use the StringLength attribute from the System.ComponentModel.DataAnnotations namespace. Here's an example of how to use it:

main.cs
using System.ComponentModel.DataAnnotations;

public class MyEntity
{
    [StringLength(50)] // Maximum 50 characters
    public string MyStringProperty { get; set; }
}
169 chars
8 lines

This ensures that the MyStringProperty property can't contain more than 50 characters.

You can also specify a minimum length:

main.cs
using System.ComponentModel.DataAnnotations;

public class MyEntity
{
    [StringLength(50, MinimumLength = 5)] // Maximum 50 characters, minimum 5 characters
    public string MyStringProperty { get; set; }
}
210 chars
8 lines

In addition to validating the length of strings, you can also use other attributes to validate the format and contents of your data, such as RegularExpression and Range.

gistlibby LogSnag