如何修复SQLite约束异常?

时间:2019-06-14 04:38:34

标签: c# sqlite xamarin xamarin.forms xamarin.android

我正在尝试使用InsertAsync将数据插入本地数据库(SQLited数据库)中。但是我一直收到这个错误。

  

sqlite.sqliteexception:sqlite.preparedsqlliteinsertcommand.executenonquery的约束

将来如何解决并避免这种情况?下面是我的示例代码。

var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();

try
{
   var caf_insert = new CAFTable
   {
      CAFNo = caf,
      EmployeeID = employeenumber,
      CAFDate = DateTime.Parse(date),
      CustomerID = retailercode,
      StartTime = DateTime.Parse(starttime),
      EndTime = DateTime.Parse(endtime),
      Photo1 = photo1url,
      Photo2 = photo2url,
      Photo3 = photo3url,
      Video = videourl,
      GPSCoordinates = actlocation,
      Remarks = remarks,
      OtherConcern = otherconcern,
      RecordLog = recordlog,
      LastUpdated = DateTime.Parse(current_datetime)
  };

      await conn.InsertOrReplaceAsync(caf_insert);
  }
  catch (Exception ex)
  {
     Crashes.TrackError(ex);
  }

这是CAF表

[Table("tblCaf")]
public class CAFTable
{
    [PrimaryKey, MaxLength(50)]
    public string CAFNo { get; set; }
    [MaxLength(50)]
    public string EmployeeID { get; set; }
    public DateTime CAFDate { get; set; }
    [MaxLength(50)]
    public string CustomerID { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string Photo1 { get; set; }
    public string Photo2 { get; set; }
    public string Photo3 { get; set; }
    public string Video { get; set; }
    public string MobilePhoto1 { get; set; }
    public string MobilePhoto2 { get; set; }
    public string MobilePhoto3 { get; set; }
    public string MobileVideo { get; set; }
    [MaxLength(2000)]
    public string Remarks { get; set; }
    [MaxLength(2000)]
    public string OtherConcern { get; set; }
    [MaxLength(2000)]
    public string GPSCoordinates { get; set; }
    [MaxLength(100)]
    public string RecordLog { get; set; }
    public DateTime LastSync { get; set; }
    public DateTime LastUpdated { get; set; }
    public int Existed { get; set; }
    public int Deleted { get; set; }
    public int ThisSynced { get; set; }
    public int Media1Synced { get; set; }
    public int Media2Synced { get; set; }
    public int Media3Synced { get; set; }
    public int Media4Synced { get; set; }
}

1 个答案:

答案 0 :(得分:3)

确保您要插入的代码中的caf值在表中不存在。