如何在EF6中创建0..1-1关系

时间:2017-04-20 15:26:29

标签: c# entity-framework entity-framework-6

我在尝试在EF中正确配置关系时遇到问题。我首先使用EF代码从现有数据库生成类。第一个表包含指令列表,第二个表包含每条指令所在状态的记录。

表格(简化):

Instruction
-----------
InstructionID
CurrentInstructionStateHistoryID

InstructionStateHistory
-----------------------
InstructionStateHistoryID
InstructionID
State

因此,您可以看到表之间存在两个关系 - 基于InstructionID的1-many关系,我对此不感兴趣,因此删除了属性。第二个关系基于CurrentInstructionStateHistoryID属性,该属性指向"当前"指令的状态。

课程如下:

public partial class Instruction
{
    [Key]
    public int InstructionID { get; set; }

    public int? CurrentInstructionStateHistoryID { get; set; }

    public virtual CurrentInstructionStateHistory InstructionStateHistory { get; set; }

}

public partial class InstructionStateHistory
{
    [Key]
    public int InstructionStateHistoryID { get; set; }

    public int InstructionID { get; set; }

    public string State { get; set; }

    public virtual Instruction tblInstruction { get; set; }
}

以下是用于定义关系的流畅API设置:

    modelBuilder.Entity<InstructionStateHistory>()
        .HasRequired(e => e.tblInstruction)
        .WithOptional(e => e.CurrentInstructionStateHistory);

所以,它都编译并运行。但是当我得到一些这样的代码时:

    Instruction instruction = await _dal.InstructionRepository.Find(claimID);
    InstructionStateHistory history = i.CurrentInstructionStateHistory;

我可以看到该指令已正确填充,让我们说Id是1234.当我检查InstructionStateHistory对象时,我想要看到的是它是什么InstructionID是1234,但我所看到的是它的 InstructionStateHistoryID ,即主键,是1234,它是什么与完全不同的指令有关。 不知何故,我需要告诉EF,Instruction.CurrentInstructionStateHistoryID链接到InstructionStateHistory.InstructionStateHistoryID。 我已经尝试了许多数据注释和流畅设置的组合,但是无法找到实际可行的组合,要么是我得到了上述结果,要么是运行时错误。感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

似乎EF无法处理这种情况,因此解决方案是忘记“当前”InstructionStateHistory的概念。相反,我在InstructionStateHistory表中添加了一个日期字段,然后将Instruction类更改为具有常规集合属性,如下所示:

public virtual ICollection<InstructionStateHistory> InstructionStateHistories{ get; set; }

然后当我需要“当前”状态时,我只查询集合,按日期排序并采用最新的集合。

相关问题