資料行對應Column 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).

資料行對應會識別哪一個資料行的資料應該從查詢,並儲存到資料庫中。Column mapping identifies which column data should be queried from and saved to in the database.

慣例Conventions

依照慣例,請將對應至名稱與屬性相同的資料行設定的每個屬性。By convention, each property will be set up to map to a column with the same name as the property.

資料註釋Data Annotations

若要設定屬性所對應的資料行,您可以使用資料註解。You can use Data Annotations to configure the column to which a property is mapped.

public class Blog
{
    [Column("blog_id")]
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Fluent APIFluent API

您可以使用 Fluent API 來設定屬性所對應的資料行。You can use the Fluent API to configure the column to which a property is mapped.

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.BlogId)
            .HasColumnName("blog_id");
    }
}

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