Had similar issue when trying to delete a model Instance which has a one-to-many relationship (Deleting a Collection that holds multiple Items).
What I did is the following:
Initialize the ModuleContainer as below.
struct MyApp: App {
private var sharedModelContainer: ModelContainer = {
let schema = Schema([
Collection.self, Item.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
let container = try ModelContainer(for: schema, configurations: [modelConfiguration])
container.mainContext.autosaveEnabled = false
return container
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
// PROPERTIES
@State private var container: ModelContainer
// INITIALIZATION
init() {
self.container = sharedModelContainer
}
//MARK: - VIEW
var body: some Scene {
WindowGroup {
RootView(modelContext: container.mainContext)
}
.modelContainer(container)
}
}
Make sure the child Model has the inverse relationship & the parent is Optional
@Model
class Item {
@Attribute(.unique) var id: UUID
var creationDate: Date
var name: String
var quantity: Int
var frequency: String
var intervalDays: Int
var packed: Bool
// Parent
@Relationship var collection: Collection?
And it worked for me.
Let me know if this hint helped.
Thank you!