最大長度Maximum Length

設定最大長度提供提示,以指定屬性来使用適當的資料類型的相關資料存放區。Configuring a maximum length provides a hint to the data store about the appropriate data type to use for a given property. 最大長度只適用於陣列資料類型,例如stringbyte[]Maximum length only applies to array data types, such as string and byte[].

注意

Entity Framework 不會進行任何驗證的最大長度,然後將資料傳遞給提供者。Entity Framework does not do any validation of maximum length before passing data to the provider. 這是由提供者或資料存放區,以驗證是否適當。It is up to the provider or data store to validate if appropriate. 比方說,當目標為 SQL Server,超出最大長度時,會導致例外狀況為基礎的資料行的資料類型將不允許儲存過多的資料。For example, when targeting SQL Server, exceeding the maximum length will result in an exception as the data type of the underlying column will not allow excess data to be stored.

慣例Conventions

依照慣例,它會保持最多資料庫提供者來選擇適當的資料類型的屬性。By convention, it is left up to the database provider to choose an appropriate data type for properties. 具有長度的屬性,資料庫提供者通常會選擇允許的最長的資料長度的資料類型。For properties that have a length, the database provider will generally choose a data type that allows for the longest length of data. 例如,Microsoft SQL Server 會使用nvarchar(max)string屬性 (或nvarchar(450)如果使用做為索引鍵資料行)。For example, Microsoft SQL Server will use nvarchar(max) for string properties (or nvarchar(450) if the column is used as a key).

資料註釋Data Annotations

若要設定屬性的最大長度,您可以使用資料註解。You can use the Data Annotations to configure a maximum length for a property. 在此範例中,目標 SQL Server,這會導致nvarchar(500)所用的資料類型。In this example, targeting SQL Server this would result in the nvarchar(500) data type being used.

public class Blog
{
    public int BlogId { get; set; }
    [MaxLength(500)]
    public string Url { get; set; }
}

關於 fluent 應用程式開發介面Fluent API

您可以使用 fluent 應用程式開發的應用程式開發介面來設定屬性的最大長度。You can use the Fluent API to configure a maximum length for a property. 在此範例中,目標 SQL Server,這會導致nvarchar(500)所用的資料類型。In this example, targeting SQL Server this would result in the nvarchar(500) data type being used.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .HasMaxLength(500);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}