0

我目前正在制作一个使用 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
4

1 回答 1

0

你能试试这个吗?

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);
于 2015-09-09T15:13:04.143 回答