loot verge
loot verge

Reputation: 449

How to fix SQLite Constraint exception?

I am trying to insert a data in my local database (SQLited Database) using InsertAsync. But I keep getting this error.

sqlite.sqliteexception: constraint at sqlite.preparedsqlliteinsertcommand.executenonquery

How can I fix and avoid this in the future? Below is my sample code.

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

Here is the CAF Table

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

Upvotes: 0

Views: 585

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

Make sure the value of caf in your code, that you're trying to insert, does not already exist in the table.

Upvotes: 3

Related Questions