【发布时间】: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