Failing to insert @Model class into managed object context

Greetings. I'm trying to insert objects into the managed context but I'm getting a runtime error "Thread 1: Cannot insert 'MyClass' in this managed object context because it is not found in the associated managed object model.". The code to set things up is pretty much straight from Apple -

var sharedModelContainer: ModelContainer = {
    let schema = Schema([
        MyClass.self,
        MyOtherClass.self
    ])
    let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

    do {
        return try ModelContainer(for: schema, configurations: [modelConfiguration])
    } catch {
        fatalError("Could not create ModelContainer: \(error)")
    }
}()

The context is being accessed through the environment like so -

public final class MyAppLogic {
    @Environment(\.modelContext) private var context
...
...
myClasses.forEach { myClass in
     context.insert(myClass)
}

Any suggestions greatly appreciated.

For background, I'm running Xcode 15.0 on macOS Ventura 13.5.2.

I am getting this same error were you ever able to resolve this?

I got this same error after adding a second .modelContainer modifier in my App struct.

Works:

.modelContainer(for: [Location.self, Bakery.self])

Didn't work:

.modelContainer(for: Location.self)
.modelContainer(for: Bakery.self)

FYI, for anyone else ending up in this thread.

I was running into this issue periodically when accessing the @Environment modelContext.insert from my view's onAppear method. Seems to me that there is probably a race condition in how the .modelContainer is setup for the view...

I moved my insert into a button clickhandler instead of the onAppear and the issue went away entirely.

Failing to insert @Model class into managed object context
 
 
Q