2013-04-29 65 views
3

在codefirst實體框架代碼優先 - 無效的列名鑑別

public partial class BaseEntity 
{ 
    public int ID { get; set; } 
} 

public partial class Fund : BaseEntity 
{ 
    public int Name { get; set; } 
} 
public partial class InvestorFund : BaseEntity 
{ 
    public int FundID { get; set; } 
} 

映射類兩類

this.Property(t => t.ID).HasColumnName("FundID"); 

我的代碼第一次加入SQL查詢

from fund in context.Funds 

join investorFund in context.InvestorFunds on fund.ID equals investorFund.FundID 

拋出一個Invalid column name Discriminator

回答

10

你需要告訴Code First這些類如何與表相關。有三個選項:每類

  • 表(TPT)將意味着基金InvestorFund定義將進入上BaseEntity定義他們自己的表和屬性會去一個名爲BaseEntity表中的字段。由於每個實體現在必須組合多個表中的字段,因此查詢速度會更慢。每個層次結構(TPH)

    modelBuilder.Entity<Fund>().ToTable("Funds"); 
    modelBuilder.Entity<InvestorFund>().ToTable("InvestorFunds"); 
    
  • 將意味着基金,InvestorFund和BaseEntity屬性都會被合併到一個名爲BaseEntity一個表,將需要一個額外的字段來指示哪一行是哪種類型。這個額外的字段被稱爲鑑別器。每個具體類型(TPC)

    modelBuilder.Entity<BaseEntity>() 
        .Map<Fund>(m => m.Requires("Discriminator").HasValue("F")) 
        .Map<InvestorFund>(m => m.Requires("Discriminator").HasValue("I")); 
    
  • 表將意味着基金和InvestorFund各自具有它們自己的表這也將包括需要他們的基類的任何字段。

    modelBuilder.Entity<Fund>().Map(m => { 
           m.MapInheritedProperties(); 
           m.ToTable("Funds"); 
    }); 
    modelBuilder.Entity<InvestorFund>().Map(m => { 
           m.MapInheritedProperties(); 
           m.ToTable("InvestorFunds"); 
    }); 
    
+0

每種類型的表(TPT) – karthi 2013-05-16 07:02:15

+0

您應該能夠使用我在TPT下編寫的代碼行來避免此錯誤。 – DamienG 2013-05-16 22:03:39

+0

在這個例子中,「類型」應該是「鑑別者」。 – 2013-11-21 18:05:42

0

您需要運行遷移。

轉到包管理器控制檯,然後在啓用自動遷移後鍵入update-database

+1

這與遷移無關。 – Jalal 2016-12-08 18:46:11