Jude
Jude

Reputation: 2433

Unable to cast object of type 'Model.Entities' to type 'System.Data.Objects.ObjectContext'

MVC3 EF5. It's running well. But when I update model from database, builds successfully but I got the exception above on the last line. When I last updated from database it was 2-3 months ago, and it was fine.

 public static ObjectContext GetContext()
 {
     Assembly testAssembly = Assembly.GetExecutingAssembly();
     Type calcType = testAssembly.GetType("Model.Entities");
     return (ObjectContext)Activator.CreateInstance(calcType);
 }

Upvotes: 1

Views: 2655

Answers (1)

StuartLC
StuartLC

Reputation: 107267

Newer versions of Entity Framework provide DbContext, as opposed to the ObjectContext that was <= EF 4.0. However, it is still possible to return a reference to the ObjectContext via IObjectContextAdapter

 Assembly testAssembly = Assembly.GetExecutingAssembly();
 Type calcType = testAssembly.GetType("Model.Entities");
 var entities = (DbContext)(Activator.CreateInstance(calcType));
 return ((IObjectContextAdapter)entities).ObjectContext;

Personally however, I would instead look at upgrading your code to return the DbContext, as it is more advanced.

Upvotes: 2

Related Questions