Go Coding
Go Coding

Reputation: 43

In C#, SQLite randomly throws "Constraint failed\r\nColumn ... is not unique"

I'm using EntityObjects in C# and my backend is SQLite. System information:

Windows XP (up-to-date), VS2010 Premium, System.Data.SQLite 1.0.88.0 (3.7.17)

The table schema is:

CREATE TABLE [transaction] (
  [primary_key_col] integer PRIMARY KEY AUTOINCREMENT, 
  [transaction_code] int NOT NULL, 
  [account_code] int NOT NULL, 
  [category_code] int NOT NULL,
  [transaction_date] date NOT NULL,
  [description] varchar(50));

public partial class Transaction : EntityObject represents this table.

To add a new Transaction, I call the following code:

Transaction transaction = new Transaction()
{
    description = _desc,
    transaction_code = generateHash(_desc),
    account_code = _acccode,
    category_code = _catcode,
    transaction_date = DateTime.Now
};

dbEntities.Transactions.AddObject(transaction);

dbEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

Works fine but after adding a few rows, I get the following exception:

Constraint failed\r\nColumn account_code is not unique.

If I exit the application and restart it, this error goes away but then randomly comes back again.

I know account_code is not unique, I never asked for it to be unique!!!

There are only 3 specific ways the application can create a transaction and this exception is thrown rather randomly from any of these methods. Is this something to do with SQLite? (I'm new to SQLite). Any idea why this is happening? I've nearly pulled out all my hair ...

Upvotes: 0

Views: 1595

Answers (1)

Rob
Rob

Reputation: 10248

As per comment which seems to have done the trick:

Are you using a "new" dbEntities context every time you do an insert or are you re-using the same one for multiple inserts? It shouldn't matter either way but I would try the former if you are currently using the latter.

Upvotes: 1

Related Questions