Implementing multiple Model Containers

Hi,

When using just one model container, I have the following code:

let modelContainer: ModelContainer
      init() {
        do {
          entriesModel = try ModelContainer(for: Model.self)
        } catch {
          fatalError("Could not initialize ModelContainer")
        }
      }

I am attempting to implement two like so:

let model1: ModelContainer
let model2: ModelContainer
    
    init() {
        do {
            model1 = try ModelContainer(for: Model1.self)
            model2 = try ModelContainer(for: Model2.self)
        } catch {
            fatalError("Could not initialize ModelContainer")
        }
    }

var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(model1)
                .modelContainer(model2)
        }
    }

However, when in the Views that I'd like to implement I don't know how to declare the models. I tried this:

@Environment(\.model1) private var model1
@Query private var data: [Model1]

But I get the error: Cannot infer key path type from context; consider explicitly specifying a root type

How do I implement multiple model containers in multiple different views?

Answered by DTS Engineer in 807048022

Is there anything that motivates you to use multiple model containers? I am super curious about that.

If your intent is to manage multiple stores, a common pattern is to use one model container + multiple configurations, as @joadan mentioned. The following post discusses the topic, and also provides a workable code example:

Regarding the error:

"But I get the error: Cannot infer key path type from context; consider explicitly specifying a root type"

It is because \.model1 is not a SwiftUI environment. To define your own environment, see EnvironmentValues.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

If you want to do something like this I believe you should have one ModelContainer but with multiple ModelConfiguration objects.

Accepted Answer

Is there anything that motivates you to use multiple model containers? I am super curious about that.

If your intent is to manage multiple stores, a common pattern is to use one model container + multiple configurations, as @joadan mentioned. The following post discusses the topic, and also provides a workable code example:

Regarding the error:

"But I get the error: Cannot infer key path type from context; consider explicitly specifying a root type"

It is because \.model1 is not a SwiftUI environment. To define your own environment, see EnvironmentValues.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Implementing multiple Model Containers
 
 
Q