插入/检索数据到Sqlite与Sqlite.net扩展

本文关键字:Sqlite 扩展 net 检索 数据 插入 | 更新日期: 2023-09-27 18:11:50

我目前正在制作一个应用程序,使用Sqlite来存储一个对象,其中有一个对象列表。我一直有麻烦试图插入和检索对象在过去的一周,想知道我是否可以得到一些帮助。任何帮助将非常感激!谢谢!

这是要以OneToMany关系存储的对象的数据库:

 [Table("Patient")]
    public class PatientDB
    {
        [PrimaryKey]
        public string ID { get; set;}
        public string Name { get; set; }
        [OneToMany(CascadeOperations = CascadeOperation.All)]
        public List<Vitals> PatientVitals { get; set;}
    }
    [Table("PatientVitals")]
    public class VitalsDB
    {
        [PrimaryKey]
        public string PatientVitalID { get; set; }
        public string Weight { get; set;}
        [ForeignKey(typeof(PatientItem))]
        public string ID { get; set; }
    }

我有一个单独的对象,它以json的形式从REST服务传递给我,我已经成功地将其反序列化为下面的对象:

 pat = new Patient
 {
     ID = "123",
     Name = "Doe",
 List<Vitals> vitals = new List<Vitals>
 {
      new Vitals
      {
         PatientVitalID = "1",
         Weight = "150",
         ID = "123"
      }
      new Vitals
      {
          PatientVitalID = "2",
          Weight = "160",
          ID = "123"
       }
  }
  };

下面是我将患者插入数据库的方法:

conn = DependencyService.Get<ISQLite>().GetConnection();
conn.CreateTable<PatientDB>();
conn.CreateTable<VitalsDB> ();

var patientToInsert = new PatientDB ();
patientToInsert.ID = pat.ID;
patientToInsert.Name = pat.Name;
conn.Insert(patientToInsert);
var vitalsToInsert = new List ();
foreach (var vital in pat.Vitals)
{
var vitalToInsert = new VitalsDB ();
vitalToInsert.PatientVitalID = vital.PatientVitalsID;
vitalToInsert.Weight = vital.Weight;
vitalsToInsert.Add(vitalToInsert);
}
conn.InsertAll (vitalsToInsert);
foreach (var vital in vitalsToInsert) 
{
vital.SmartCardID = patientToInsert.SmartCardID;
conn.Update (vital);
}

这是我如何检索病人的

public List<PatientDB> retrieveDBPatient(string ID)
{
    return conn.Query<PatientDB> ("SELECT * FROM [Patient] WHERE [ID]= '" + ID + "'");
}

最后,错误消息

SQLite.Net.SQLiteException: Constraint
at SQLite.Net.PreparedSqlLiteInsertCommand.ExecuteNonQuery (System.Object[] source) [0x0016b] in <filename unknown>:0
at SQLite.Net.SQLiteConnection.Insert (System.Object obj, System.String extra, System.Type objType) [0x000bc] in <filename unknown>:0

插入/检索数据到Sqlite与Sqlite.net扩展

你能试试吗?

conn = DependencyService.Get().GetConnection();
conn.CreateTable();
var patientToInsert = new PatientDB();
patientToInsert.ID = pat.ID;
patientToInsert.Name = pat.Name;
patiendToInsert.PatientVitals = new List();
foreach (var vital in pat.Vitals)
{
    var vitalToInsert = new VitalsDB();
    vitalToInsert.PatientVitalID = vital.PatientVitalsID;
    vitalToInsert.Weight = vital.Weight;
    patiendToInsert.PatientVitals.Add(vitalToInsert);
}
conn.Insert(patientToInsert);