資料表對應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>
公開衍生內容上的實體的屬性。By convention, each entity will be setup 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 應用程式開發介面Fluent API
若要設定類型會對應至資料表,您可以使用 fluent 應用程式開發的應用程式開發介面。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");