实体框架代码首先是外键选择查询问题

时间:2013-03-27 07:16:32

标签: entity-framework c#-4.0 entity-framework-4.1

我有一个POCO,它有一个看起来像这样的外键

public partial class DataFileInformation
{
    public DataFileInformation()
    {
    }

    public int ID { get; set; }
    public int? HistoryID { get; set; }
    public string FileName { get; set; }
    public int NumberOfLines { get; set; }
    public string UpdatedByPersonnelNumber { get; set; }
    public DateTime UpdatedDateTime { get; set; }    
    public virtual JobHistory History { get; set; }
}

public partial class JobHistory
{    
    public int ID { get; set; }
    public Nullable<DateTime> StartDate { get; set; }
    public Nullable<DateTime> EndDate { get; set; }
    public Nullable<DateTime> UpdatedDateTime { get; set; }    
}

映射:

class DataFileUploadInformationEntityMap : EntityTypeConfiguration<DataFileInformation>
{
    public DataFileUploadInformationEntityMap ()
    {
        ToTable("DataFileInformationsView");
        HasKey(fileMetaData => fileMetaData.ID);
        HasOptional(file => file.History)
            .WithMany().HasForeignKey(file => file.HistoryID);
    }
}

public class JobHistoryEntityMap : EntityTypeConfiguration<JobHistory>
{
    public JobHistoryEntityMap()
    {
        ToTable("JobHistoryView");
        HasKey(job => job.ID);
    }
}

即使使用配置,动态查询也会被触发,如下所示

exec sp_executesql N'SELECT  
    [Extent1].[ID] AS [ID],
    [Extent1].[DataFileInformation_ID] AS [DataFileInformation_ID], 
    [Extent1].[FileName] AS [FileName], 
    [Extent1].[UpdatedByPersonnelNumber] AS [UpdatedByPersonnelNumber],
    [Extent1].[UpdatedDateTime] AS [UpdatedDateTime],
    [Extent1].[JobID] AS [LoaderJobID],
    [Extent1].[JobHistory_ID] AS [JobHistory_ID],
    [Extent2].[ID] AS [ID1],
    [Extent2].[StartDate] AS [StartDate],
    [Extent2].[EndDate] AS [EndDate],
    [Extent2].[UpdatedByPersonnelNumber] AS [UpdatedByPersonnelNumber1],
    [Extent2].[CreateDate] AS [CreateDate],
    FROM   [DataFileInformationsView] AS [Extent1]
    LEFT OUTER JOIN [JobHistoryView] AS [Extent2] 
        ON [Extent1].[LoaderJobID] = [Extent2].[ID] 
    WHERE [Extent1].[ID] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=146

生成的动态查询无法将JobHistory_ID和DataFileInformation_ID映射到POCO,EF会抛出无法找到列的异常

1 个答案:

答案 0 :(得分:1)

DataFileInformation映射的类名不正确,可选外键的属性名称为

class FileUploadInformationEntityMap :
    EntityTypeConfiguration<DataFileInformation>
{
    public FileUploadInformationEntityMap()
    {
        ToTable("DataFileUploadInformationEntity");
        HasKey(f => f.ID);
        HasOptional(f => f.History); // here you have LoaderJobHistory
    }
}

还要确保您正在查看正确的SQL,因为从SQL我看到名称DataFileInformationsViewJobHistoryView,但映射提供了表名DataFileUploadInformationEntityJobHistoryEntity。而且您不需要指定HasOptional - 默认情况下FK可以为空。


更新问题后,您的映射应该有效。您还可以添加级联删除配置(但这不是必需的)

HasOptional(f => f.History)
    .WithMany()
    .HasForeignKey(f => f.HistoryID)
    .WillCascadeOnDelete(false);