OneToOne CascadeDelete Not Working
Hi,
I have 2 tables with OneToOne relationship:
[Table("Account")]
public class Account
{
[PrimaryKey, AutoIncrement, NotNull]
public int Id { get; set; }
[ForeignKey(typeof(Individual))]
public int IndividualId { get; set; }
[OneToOne(CascadeOperations = CascadeOperation.CascadeDelete)]
public Individual Individual { get; set; }
}
[Table("Individual")]
public class Individual
{
[PrimaryKey, AutoIncrement, NotNull]
public int Id { get; set; }
public string Title { get; set; }
}
When I delete a row in Account table with _database.DeleteAsync(account); code, the row in Account table deleted successfully but the row related to it in the Individual table remains and not deleted.
What is wrong here?
Comments (5)
-
-
reporter Ok. Now I use code below to delete the row but none of them works:
_database.Delete(individual, true); // Just delete the row in individual table // OR _database.Delete(account, true); // Just delete the row in account table
And this is the code to create tables: (For more information)
var connPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, DbName); _dbConnection = new SQLiteConnection(new SQLitePlatformWinRT(), connPath); _dbConnection.CreateTable<Individual>(); _dbConnection.CreateTable<Account>();
What is the problem?
-
_database.Delete(individual, true);
won't work because you haven't defined the relationshipIndividual
->Account
, but deleting the account should delete the individual if the relationship is set. Take into account that the relationships must've been loaded into memory in order to cascade deletion to work. Ifaccount.Individual
isnull
, the individual won't be deleted.You have a working sample of cascade deletion in the
RecursiveWriteTests
integration test. Can you check if that sample works for you? -
reporter You are right.
I have to set account.Individual to delete both of them.
Thank you for your help.
-
reporter - changed status to resolved
- Log in to comment
You are not using a SQLite-Net Extensions method to delete the objects, you are using a plain SQLite-Net method that has no clue about relationships. You have to use the Delete method with recursive parameter set to true.