一对多关系数据库

OneToMany Relational Database

我有以下 json 对象,我试图将它们存储在 sqlite 中的两个不同的 table 中。这是场景,我先下载一组学生并检查数据库,一切看起来都很棒。

但是,当我让另一组学生插入现有的 table 时。少数 StudentId 的第一组数据集为 NULL,但最新数据集的 StudentId 是正确的。

更详细地说,你们在 StudentSpecifications table 中有很多相同的 studentId。如果要插入的第二个数据集具有相同的 StudentId,那么它们会影响第一个数据集并使它们成为 NULL,但第二个数据集 StudentId 是正确的。

StudentId 用作 ForeignKey。我怀疑我用的是OnetoMany关系,但不知如何处理?

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",
   },
  }
]

Student.cs

[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<StudentSpecification> StudentSpecifications { get; set; }

public Student(StudentDto dto)
{
    Id = dto.StudentId.ToString();
    Name = dto.Name;
    QualificationId = dto.QualificationId.ToString();
    StudentSpecifications= dto.StudentSpecification.Select(x => new StudentSpecification(x, Id)).ToList();
} 

StudentSpecification.cs

[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;
    }

正在插入 table

public bool AddOrUpdate(IEnumerable<T> entities, bool withChildren = false)
{
  var db = _factory.GetConnectionWithLock();
  using (db.Lock())
  {
     db.InsertOrReplaceAllWithChildren(entities, true);
     return true;
   }
}

每次在此处保存新数据集时,您都在覆盖关系:

StudentSpecifications= dto.StudentSpecification.Select(x => new StudentSpecification(x, Id)).ToList();

因此,通过将外键设置为 null,您的旧 StudentSpecifications 将从数据库中的关系中删除。

问题是您想要合并这些结果,因此您可以从数据库中加载之前的元素并手动合并它们,或手动处理关系。

由于您已经手动分配了外键,因此您可以使用普通的 SQLite-Net 方法插入对象:

db.InsertOrReplace(student);
for (var spec in student.StudentSpecifications) {
    db.InsertOrReplace(spec);
}

这样您的旧关系就不会被删除,下次您从数据库加载结果时将合并这些结果。