必要和選擇性的屬性Required and Optional Properties

屬性會被視為選擇性是否有效,才能包含nullA property is considered optional if it is valid for it to contain null. 如果null不是有效的值,以指派給屬性,則它會被視為必要的屬性。If null is not a valid value to be assigned to a property then it is considered to be a required property.

慣例Conventions

依照慣例,其 CLR 類型可以包含 null 的屬性會設定為選擇性 (stringint?byte[]等。)。By convention, a property whose CLR type can contain null will be configured as optional (string, int?, byte[], etc.). 將設定其 CLR 類型不能包含 null 的屬性視需要 (intdecimalbool等。)。Properties whose CLR type cannot contain null will be configured as required (int, decimal, bool, etc.).

注意

CLR 類型不能包含 null 的屬性無法設定為選擇性。A property whose CLR type cannot contain null cannot be configured as optional. 此屬性將一律視為 Entity Framework 所需。The property will always be considered required by Entity Framework.

資料註釋Data Annotations

您可以使用資料註解表示是必要屬性。You can use Data Annotations to indicate that a property is required.

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

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

您可以使用 fluent 應用程式開發的應用程式開發介面,表示是必要屬性。You can use the Fluent API to indicate that a property is required.

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

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

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