I debugged this problem in WinDbg and It's caused by the following Microsoft.VisualStudio.Web.Mvc.Scaffolding.BuiltIn.EntityFrameworkServices
method:
internal static bool IsValidContextType(Type contextType)
{
return (typeof(ObjectContext).IsAssignableFrom(contextType) || ((contextType.BaseType != null) && contextType.BaseType.FullName.Equals("System.Data.Entity.DbContext", StringComparison.OrdinalIgnoreCase)));
}
This method is returning false because it is being passed the wrong Type. I'm not sure where they come from, but there are multiple DLLs loaded inside VS that contain implementations of the context type, but only one of them is Derived From DbContext - all the others are derived from System.Object. these bogus types' assemblies are in my '%localappdata%\assembly' directory, so they've been auto-generated by some tool and loaded into VS.
The bug is caused by the fact that Microsoft.VisualStudio.Web.Mvc.Util.TypeHelper.GetType
only filters by Type.FullName. in order to find the correct Type it's also necessary to filter by IsValidContextType()
.
Ok, something really weird is going on. I have 2 partial classes for my DbContext-derived class (most of it is auto-generated by a .tt script, and some is hand-crafted). when i try to add a controller, VS adds new properties to my partial class, then it builds that part of the partial class (only the manual part, and it doesn't use the base class). then it loads that DLL that it built from half the model class into memory, then it fails the base-class check above.
weird.
bottom line: try removing partial classes of your model context, if you have one.