[ad_1]
I’ve looked at this code every which way. Searched here for a solution. I discovered that autogenerated primary key field can’t be used as a parent column Stack question here. However I have used it in java, but it doesn’t seem to be working in Kotlin (which I’m trying to learn).
Here are my classes:
User.class
@Entity
@Parcelize
data class User(
@PrimaryKey(autoGenerate = true) val id: Long,
val email: String,
val name: String,
val defaultRecipient: String
) : Parcelable
===
University.class
@Parcelize
@Entity(
foreignKeys = [ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["userId"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)], indices = [Index(value = ["userId"])]
)
data class University(
val userId: Long,
@PrimaryKey @NonNull val name: String
) : Parcelable {
override fun equals(other: Any?): Boolean {
if(other !is University) return false
return (this.name == other.name) && this.userId == other.userId
}
override fun toString(): String {
return this.name
}
}
===
Semester.class
@Parcelize
@Entity(
foreignKeys = [ForeignKey(
entity = University::class,
parentColumns = ["name"],
childColumns = ["universityName"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)], indices = [Index(value = ["universityName"])]
)
data class Semester(
val title: String,
val universityName: String,
@PrimaryKey(autoGenerate = true) val id: Long
) : Parcelable
===
Course.class
@Parcelize
@Entity(
foreignKeys = [ForeignKey(
entity = Semester::class,
parentColumns = ["id"],
childColumns = ["semesterId"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)], indices = [Index(value = ["semesterId"])]
)
data class Course(
val title: String,
val code: String,
val semesterId: Long,
@PrimaryKey(autoGenerate = true) val id: Long
) : Parcelable
When I try to execute the following code, I get a foreign key constraint error:
val user = userDao.getUser()
userDao.insertUniversity(University(user.id, "Chuckles University"))
val university = userDao.getUniversitiesByUser(user.id)[0]
userDao.insertSemester(Semester("Fall 22", "Comsats Wah", 0))
val semester = userDao.getSemestersByUniversity(university.name)[0]
userDao.insertCourse(Course("Introduction to Programming", "CSC100", semester.id, 0))
[ad_2]