0

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

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

studentId更详细地说,您在StudentSpecifications表中也有相同的内容。如果要插入的第二个数据集具有相同的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",
   },
  }
]

学生.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();
} 

学生规范.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;
    }

插入表格

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

1 回答 1

1

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

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

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

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

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

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

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

于 2017-02-21T18:21:09.183 回答