2013-04-29 61 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