title: OneToMany Relational Database
body: <p>I have the following json object, where I am trying to store them in two different tables in the sqlite. Here is the scenario, I download a set a students first and check the database, and everything looks great. </p>
  
  <p>However, when I get another set of students to insert to the existing tables.  few <code>StudentId</code>'s gets NULL for the first set of the dataset, but the latest dataset's <code>StudentId</code> is right. </p>
  
  <p>In more detail, you many have same <code>studentId</code> in the <code>StudentSpecifications</code> table. If the second dataset which is going to be inserted has the same <code>StudentId</code>, those affects the first dataset and make them <code>NULL</code>, but the second dataset <code>StudentId</code> is right.</p>
  
  <p>StudentId is used as a <code>ForeignKey</code>. I suspect that I am using <code>OnetoMany</code> relationship, but I do not know how to handle? </p>
  
  <pre><code>Student: [
  {
    StudentId: "3322449c-cd89-4633-ae3a-4578572eeeee",
    Name: "Joseph Peter",
    Qualification: "1222449c-efds-rfcs-asde-8546242kkkkk",
    StudentSpecifications: [
    {
      Id: "45e63840-0dc3-4296-a83d-97cc462b2dac",
      EnrollDate: "2016-08-05T09:40:21.233",
      GraduationDate: "2017-06-05T09:40:21.233",
     },
     {
      Id: "25fffe40-0dc3-4296-a83d-97cc462b2dac",
      EnrollDate: "2015-07-05T09:40:21.233",
      GraduationDate: "2016-08-05T09:40:21.233",
     },
    }
  ]
  </code></pre>
  
  <p><strong>Student.cs</strong></p>
  
  <pre><code>[OneToMany(CascadeOperations = CascadeOperation.All)]
  public List&lt;StudentSpecification&gt; StudentSpecifications { get; set; }
  
  public Student(StudentDto dto)
  {
      Id = dto.StudentId.ToString();
      Name = dto.Name;
      QualificationId = dto.QualificationId.ToString();
      StudentSpecifications= dto.StudentSpecification.Select(x =&gt; new StudentSpecification(x, Id)).ToList();
  } 
  </code></pre>
  
  <p><strong>StudentSpecification.cs</strong></p>
  
  <pre><code>[Table("STUDENT_SPECIFICATIONS")]
  public class StudentSpecification
  {
      [PrimaryKey]
      public string Id{get;set;}
      [ForeignKey(typeof(Student))]
      public string StudentId { get; set; }
      public DateTime EnrollDate{ get; set; }
      public DateTime GraduationDate{ get; set; }
  
      public StudentSpecification(StudentDto dto, string studentId)
      {
          Id = Guid.NewGuid().ToString();
          StudentId = studentId;
          EnrollDate= dto.EnrollDate;
          GraduationDate= dto.GraduationDate;
      }
  </code></pre>
  
  <p>Inserting into the table</p>
  
  <pre><code>public bool AddOrUpdate(IEnumerable&lt;T&gt; entities, bool withChildren = false)
  {
    var db = _factory.GetConnectionWithLock();
    using (db.Lock())
    {
       db.InsertOrReplaceAllWithChildren(entities, true);
       return true;
     }
  }
  </code></pre>