【问题标题】:OneToMany Relational Database一对多关系数据库
【发布时间】:2017-02-20 16:47:12
【问题描述】:

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

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

更详细地说,StudentSpecifications 表中有许多相同的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;
    }

插入表格

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

【问题讨论】:

  • 你能把Student.cs的代码贴出来吗?好像不完整,不能用OneToMany注释类。
  • @redent84,你是对的,这是我的错误。我已经添加了缺失的部分。

标签: c# database sqlite xamarin sqlite-net-extensions


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2017-03-18
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多