資料表對應Table Mapping

注意

本節中的組態一般適用於關聯式資料庫。The configuration in this section is applicable to relational databases in general. 當您因共用 Microsoft.EntityFrameworkCore.Relational 套件而安裝關聯式資料庫提供者時,這裡顯示的擴充方法會變成可用。The extension methods shown here will become available when you install a relational database provider (due to the shared Microsoft.EntityFrameworkCore.Relational package).

資料表對應會識別應該從查詢並儲存到資料庫中的資料表資料。Table mapping identifies which table data should be queried from and saved to in the database.

慣例Conventions

依照慣例,每個實體會設定為對應至具有相同名稱的資料表DbSet<TEntity>衍生內容上的實體公開 (expose) 的屬性。By convention, each entity will be set up to map to a table with the same name as the DbSet<TEntity> property that exposes the entity on the derived context. 如果沒有DbSet<TEntity>是否包含指定之實體,會使用類別名稱。If no DbSet<TEntity> is included for the given entity, the class name is used.

資料註釋Data Annotations

若要設定的類型會對應至資料表,您可以使用資料註解。You can use Data Annotations to configure the table that a type maps to.

using System.ComponentModel.DataAnnotations.Schema;
[Table("blogs")]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

您也可以指定資料表所屬的結構描述。You can also specify a schema that the table belongs to.

[Table("blogs", Schema = "blogging")]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Fluent APIFluent API

您可以使用 Fluent API 來設定類型會對應至資料表。You can use the Fluent API to configure the table that a type maps to.

using Microsoft.EntityFrameworkCore;
class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .ToTable("blogs");
    }
}

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

您也可以指定資料表所屬的結構描述。You can also specify a schema that the table belongs to.

        modelBuilder.Entity<Blog>()
            .ToTable("blogs", schema: "blogging");