0

我有一个 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 抛出异常无法找到列

4

1 回答 1

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);
于 2013-03-27T07:41:24.327 回答