我的应用程序目前正在使用改造和空间,但我正在努力寻找一种自动化DB对象ID的方法。将翻新对象映射到RoomDB实体时,即使我添加了自动化键

问题描述 投票:0回答:1

@Entity data class ProductEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int, @ColumnInfo(name = "productId") val productId: String, @ColumnInfo(name = "types") val types: List<String>, )

the映射器如下:

fun RetrofitProduct.toEntity(): ProductEntity { return ProductEntity( productId = this.id, types = this.types, ) }
但在构建时间,编译器抱怨我需要添加

id


参数“id'

我希望该ID由房间生成,以获取我的页面的项目数量。
基本上,如果我拉上lastItem,我知道与ID一起使用:25。所以我需要要求26及更多。

在使用房间和自动生成的ID时,这实际上是一个很常见的陷阱。
问题在于,即使您将ID标记为自动源= True,Kotlin仍然需要在构造函数中提供所有参数,因为Productentity是数据类。这是解决此问题的几种方法:

最快的修复 - 提供默认值为0:

kotlinCopy@Entity data class ProductEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int = 0, // Add this default value @ColumnInfo(name = "productId") val productId: String, @ColumnInfo(name = "types") val types: List<String>, )

或如果您希望在映射器中更加明确:

kotlinCopyfun RetrofitProduct.toEntity(): ProductEntity { return ProductEntity( id = 0, // Room will ignore this and auto-generate productId = this.id, types = this.types, ) }

android kotlin android-room
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.