创建并配置模型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.

using Microsoft.EntityFrameworkCore;

namespace EFModeling.Configuring.FluentAPI.Samples.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; }
    }
}

使用数据注释来配置模型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.

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace EFModeling.Configuring.DataAnnotations.Samples.Required
{
    class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    }

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