如何使用实体框架添加带有外键的记录?

时间:2011-12-13 20:55:13

标签: sql linq sql-server-2008 entity-framework entity-framework-4.1

我正在尝试通过像这样的XML文件向我的数据库添加记录:

<Answers ExamID="1" StudentID="abcd" Date="10/26/2011 11:50:34 AM" Seed="495"
      IsSED="False">
  <Summary>
    <Objective ID="1" MakeUp="False" Quantify="5" Difficulty="Easy"
         Accredited="True" Produced="True">
      <Details Result="0" Date="10/26/2011 11:35:18 AM" />
      <Details Result="1" Date="10/26/2011 11:50:34 AM" />
    </Objective>
    <Objective ID="2" MakeUp="True" Quantify="5" Difficulty="Easy"
         Accredited="False" Produced="True">
      <Details Result="0" Date="10/26/2011 11:35:18 AM" />
      <Details Result="0" Date="10/26/2011 11:50:34 AM" />
    </Objective>
  </Summary>
  <Answer ProblemID="0" ObjectiveID="1" IsCorrect="True" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="9" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="1" IsCorrect="True" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="20" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="1" IsCorrect="True" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="16" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="1" IsCorrect="True" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="36" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="1" IsCorrect="True" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="18" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="2" IsCorrect="False" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="Null" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="2" IsCorrect="False" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="Null" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="2" IsCorrect="False" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="Null" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="2" IsCorrect="False" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="Null" />
  </Answer>
  <Answer ProblemID="0" ObjectiveID="2" IsCorrect="False" Difficulty="Easy">
    <Result DataType="System.Decimal" Value="Null" />
  </Answer>
</Answers>

请检查图表。我需要获取一些数据来向EXAM PRODUCED,EXERCISE和ANSWER表(实体)添加记录。

在EXAM PRODUCED中,我有一个名为ExamID hide的字段。我的主要问题是,如何将当前文件引用到考试中?

您认为我需要创建存储过程吗?SQL SERVER必须这样做吗? 或者使用Linq to SQL?

我对这种情况有点困惑。

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以将ExamProduced个实例添加到ExamsProduced的{​​{1}}集合中。 DbContext将在插入时设置ExamId。