簡體   English   中英

實體框架中的每種類型Fluent映射表

[英]Table Per Type Fluent Mapping in Entity Framework

使用Entity Framework,我可以將相關表映射為類繼承。有三種不同的方法來表示繼承層次結構(通過weblogs ):

  • 每個層次表(TPH)
  • 每種類型的表(TPT)
  • 每個混凝土等級表(TPC)

網站mscblogs對這些方法中的每一種都有一個很好的解釋。

我試圖了解如何使用方法TPT(每種類型的表)來映射我的表,但與mscblogs的示例不同,我需要為流暢的編程執行映射,如:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

public class BillingDetailMap : EntityTypeConfiguration<BillingDetailEntity>
{
    public BillingDetailMap()
    {
        // ...
        this.Property(t => t.Number).HasColumnName("Number");
        // ...
    }    
}

// ...

我正在尋找幾個小時,但我找不到任何東西。 我發現了許多如何用圖表屬性其他方法做到這一點的例子,但沒有流暢的api。

如何在Entity Framework 4.1 Fluent API中映射TPT?

映射每個類型的表(TPT)繼承

在TPT映射方案中,所有類型都映射到各個表。 僅屬於基本類型或派生類型的屬性存儲在映射到該類型的表中。 映射到派生類型的表還存儲將派生表與基表連接的外鍵。

modelBuilder.Entity<Course>().ToTable("Course");  
modelBuilder.Entity<OnsiteCourse>().ToTable("OnsiteCourse");

資源

檢查之前的問題的答案 ,希望它有所幫助。

更新完整示例

public class AppContext : DbContext
{
    public DbSet<Item> Items { get; set; } // --> this dbset is required for TPT, if removed it will become TPCC
    public DbSet<Food> Books { get; set; }
    public DbSet<Book> Foods { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ItemMap());
        modelBuilder.Configurations.Add(new BookMap());
    }
}
public class ItemMap : EntityTypeConfiguration<Food>
{
    public ItemMap()
    {
        ToTable("Foods");
    }
}
public class BookMap : EntityTypeConfiguration<Book>
{
    public BookMap()
    {
        ToTable("Books");
    }
}
public abstract class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Food : Item { }
public class Book : Item { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM