From 729fc83325ba4e990170f2decfcc9dec77fffc81 Mon Sep 17 00:00:00 2001 From: "Robert McLaws (Microsoft MVP)" Date: Wed, 28 Sep 2016 09:22:33 -0400 Subject: [PATCH] Fix ModelProducer to handle multiple APIs with different DbContexts Fixes #527. --- .../Model/ModelProducer.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.Restier.Providers.EntityFramework/Model/ModelProducer.cs b/src/Microsoft.Restier.Providers.EntityFramework/Model/ModelProducer.cs index b67228b9..8f03deb6 100644 --- a/src/Microsoft.Restier.Providers.EntityFramework/Model/ModelProducer.cs +++ b/src/Microsoft.Restier.Providers.EntityFramework/Model/ModelProducer.cs @@ -62,7 +62,19 @@ public Task GetModelAsync(ModelContext context, CancellationToken can var dbContext = context.GetApiService(); var efModel = (dbContext as IObjectContextAdapter).ObjectContext.MetadataWorkspace; - var efEntityContainer = efModel.GetItems(DataSpace.CSpace).Single(); + var efEntityContainers = efModel.GetItems(DataSpace.CSpace); + var efEntityContainer = efEntityContainers.FirstOrDefault(c => c.Name == dbContext.GetType().Name); + if (efEntityContainer == null) + { + if (efEntityContainers.Count > 1) + { + var containerNames = efEntityContainers.Aggregate("", (current, next) => next.Name + ", "); + throw new Exception("This project has multiple EntityFrameworkApis using different DbContexts, and the correct contect could not be loaded. \r\n" + + $"The contexts available are '{containerNames.Substring(0, containerNames.Length - 2)}' but the Container expects '{efEntityContainer.Name}'."); + } + throw new Exception("Could not find the correct DbContext instance for this EntityFrameworkApi. \r\n" + + $"The Context name was '{dbContext.GetType().Name}' but the Container expects '{efEntityContainer.Name}'."); + } var itemCollection = (ObjectItemCollection)efModel.GetItemCollection(DataSpace.OSpace); foreach (var efEntitySet in efEntityContainer.EntitySets)