Skip to content

Commit

Permalink
Fix ModelProducer to handle multiple APIs with different DbContexts
Browse files Browse the repository at this point in the history
Fixes OData#527.
  • Loading branch information
Robert McLaws (Microsoft MVP) authored Sep 28, 2016
1 parent 68e14c4 commit 729fc83
Showing 1 changed file with 13 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,19 @@ public Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken can
var dbContext = context.GetApiService<DbContext>();

var efModel = (dbContext as IObjectContextAdapter).ObjectContext.MetadataWorkspace;
var efEntityContainer = efModel.GetItems<EntityContainer>(DataSpace.CSpace).Single();
var efEntityContainers = efModel.GetItems<EntityContainer>(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)
Expand Down

0 comments on commit 729fc83

Please sign in to comment.