R. SAM
R. SAM

Reputation: 53

Android Room On delete Cascade doesn't work

I know there are a lot of posts about this kind of subject but they all deal with SQLite... (mine is about Room).

I have a one-to-many relation between a "Card" table and a "Deck" table. So a card has 1 Deck and a Deck has Many cards. Insertion and Deletion are OK for 1 row but i'd like to delete the cards of a deck when this one is removed : on Delete cascade relationship.

My code :

(Card.class)

@Entity(tableName = "cards")
public class Card{

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public int id;

    @ColumnInfo(name = "face1")
    public String face1;

    @ColumnInfo(name = "face2")
    public String face2;

    @ColumnInfo(name = "id_deck")
    @ForeignKey(entity = Deck.class, parentColumns = "id", childColumns = 
    "id_deck", onDelete = CASCADE)
    public int id_deck;
}

Deck.class :

@Entity(tableName = "decks")
public class Deck {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public int id;

    @ColumnInfo(name = "nom")
    public String nom;

    public Deck(String nom){
        this.nom = nom;
    }

}

Did i make something wrong ? When I remove a Deck, the cards still exist.

Upvotes: 4

Views: 3642

Answers (1)

musooff
musooff

Reputation: 6852

You should define your foreign keys inside your @Entity annotation.

@Entity(tableName = "cards", foreignKeys = @ForeignKey(entity = Deck.class, parentColumns = "id", childColumns = "id_deck", onDelete = CASCADE))

Update for Kotlin

@Entity(tableName = "cards", foreignKeys = [ForeignKey(entity = Deck::class, parentColumns = ["id"], childColumns = ["id_deck"], onDelete = ForeignKey.CASCADE)])

Upvotes: 9

Related Questions