建立和設定模型Creating and configuring a Model

Entity Framework 會使用一組慣例,根據您實體類別的圖形建置模型。Entity Framework uses a set of conventions to build a model based on the shape of your entity classes. 您可以指定其他組態來補充及 (或) 覆寫慣例探索到的項目。You can specify additional configuration to supplement and/or override what was discovered by convention.

本文涵蓋可套用至將目標設為任何資料存放區之模型的組態,以及將目標設為任何關聯式資料庫時可套用的組態。This article covers configuration that can be applied to a model targeting any data store and that which can be applied when targeting any relational database. 提供者也可以啟用特定資料存放區專屬的組態。Providers may also enable configuration that is specific to a particular data store. 針對提供者專屬組態的文件,請參閱資料庫提供者一節。For documentation on provider specific configuration see the Database Providers section.

提示

您可以在 GitHub 上檢視此文章的範例You can view this article’s sample on GitHub.

使用 Fluent API 設定模型Use fluent API to configure a model

您可以覆寫衍生內容中的 OnModelCreating 方法,並使用 ModelBuilder API 來設定模型。You can override the OnModelCreating method in your derived context and use the ModelBuilder API to configure your model. 這是最強大的組態方法,讓您能夠指定組態而不修改實體類別。This is the most powerful method of configuration and allows configuration to be specified without modifying your entity classes. Fluent API 組態具有最高的優先順序,且會覆寫慣例及資料註解。Fluent API configuration has the highest precedence and will override conventions and data annotations.

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

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

使用資料註解Use data annotations to configure a model

您也可以將屬性 (又稱資料註解) 套用到類別及屬性。You can also apply attributes (known as Data Annotations) to your classes and properties. 資料註解會覆寫慣例,但會受到 Fluent API 組態覆寫。Data annotations will override conventions, but will be overridden by Fluent API configuration.

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