jeudi 31 mars 2016

Foreign Key constraint failed - SQLite with Entity Framework

I have a two tables in database with 1 to Many relationship like this:

Job:

iID, Other columns...

Mailbox:

iID, iJobID, Other columns...

where

a Job can contain many Mailboxes and iID column of both tables is set to auto increment.

The Mailboxes are added in collection of Job and the parent entity (Job) is then added to database and SaveChanges() is called, like this:

Job foo = new Job
{
  strJobName = "fooJob",
  //other properties...

  Mailboxes = collectionOfMailboxes;
};

dbContext.Jobs.Add(foo);

dbContext.SaveChanges();

where

Mailboxes is the child collection property generated by EF.

Everything works fine up to this point. Mailboxes and Job both are added to database with foreign key relation.

But then I needed to enable the foreign key constraint for which I read here that SQLite doesn't enforce it by default. So I did it by adding

foreign keys=true;

in the connection string, which I read here and here but after adding the constraint I'm no longer able to add a Job record. and I get:

System.Data.SQLite.SQLiteException: constraint failed FOREIGN KEY

If I remove the constraint then my code works fine. Why is this happening and how can I add foreign key constraint in EF so that it is checked after adding the record.

Aucun commentaire:

Enregistrer un commentaire