There is a much simpler approach. You don't have to use @ModelActor macro or implement ModelActor protocol. Apple have got it wrong. Database code should never execute on the main thread. Instead I'm doing my own thing:
actor ProjectRepository: ProjectStorage {
nonisolated let modelExecutor: any ModelExecutor
nonisolated let modelContainer: ModelContainer
private var modelContext: ModelContext { modelExecutor.modelContext }
init(modelContainer: ModelContainer) {
assertOnMainThread() // Custom function
self.modelExecutor = DefaultSerialModelExecutor(modelContext: ModelContext(modelContainer))
self.modelContainer = modelContainer
}
func persist() throws {
assertNotOnMainThread() // Custom function
try modelContext.save()
}
}
Works like a charm.