When defining models with Entity Framework’s Code First and a DbContext class, I find the “View Model” feature of the Entity Framework Power Tool completely indispensable. Without it, I only *think* I know what I’ve told EF my model should be but I don’t really know how Code First will interpret the information I’ve provided (class structures, DbSets, configurations).
For example, I may have a set of classes but a DbContext that only specifies a single DbSet:
public class CustomerServiceContext : DbContext { public DbSet<Customer> Customers { get; set; } }
But because of relationships from Customer to other types and their relationships to even other types, using it’s base rules (convention) Code First interprets your entire model as
Another common point of mapping confusion is with relationships. Being able to visualize how Code First interprets the model can show me where, for example, I’ve attempted to define a 1:1 relationship but in fact, I’ve defined a 1:0..1 which will really create problems down the road in my application.
I use the tool to show me where I haven’t configured things properly and fix my mappings (via convention or configurations) until the visual model aligns with my intention.
So I really can’t live without this tool and I show it to everyone I can.
Currently the tool is something you install as an extension to Visual Studio. It’s called Entity Framework Power Tools Beta 3 and it works even wtih the latest update to VS (Visual Studio 2012 Update 2).
While there are other features, with the tool installed, you can point to any class that inherits from DbContext, right click and see “Entity Framework” on the context menu. Select Entity Framework and you’ll see four options. My focus is on the first of these “View Entity Data Model (Read-only).
But half the time I show it, it doesn’t work and it’s always something I’ve done wrong and forgotten about.
Designer Problems != Modeling Problems
If there is a problem with your model, you’ll get a helpful error message in the output window. This is about what’s wrong with your mappings. One common one is you tried to create a one to one mapping but haven’t given code first enough detail (e.g. it needs to know which is the principal and which is the dependent).
The focus of this blog post however is problems I encounter with getting the tool to perform it’s task.
Most Common Reason that the Designer Fails: Can’t Find the Connection String
Even though the designer is not going to touch the database to generate the view, it still needs to have access to a connection string.
But when it can’t find it, it doesn’t always tell you that it can’t find the connection string.
Typically I get an error message that says: “sequence contains no matching element”.
Another is “Exception has been thrown by the target of an invocation”.
Designer Looks for the Connection String in the Startup Project of a Solution
This is the A#1 reason that the designer won’t work. It’s a bit of a pain because you don’t really want to set things up for the designer, but for debug mode. It doesn’t matter if the startup project is executable. It just has to be some project with a config file and in the config file, valid connection information ( a connection string or connection info in the Entity Framework section) that EF will look for.
Designer Will Not Look Inside Solution or Project Folders
This is my A#2 reason the designer won’t work. I like to organize my solutions. I organize projects into solution folders and I organize code into project folders. If you config file is in a folder, the designer won’t find it.
My Typical Setup for Success
So I have a separate project in my solution that is NOT inside a folder just to help me use this critical designer tool. Thanks to Vaughn Vernon for helping me find a better name for the project than I had been using that makes it very clear that this has nothing to do with my application at all.
So when I need to view a model, as long as I remember to set that project as the startup project in my solution, the designer is able to do it’s job. Here is an example of using this for a context that doesn’t even inherit DbContext directly. It inherits from my own class “BaseContext” which inherits from DbContext. The designer is able show me the visual model even with this extra abstraction.
Another Weird Error that Is Not About the Connection String: “A constructible type …”
Thanks to Ethan in comments for pointing out this one. I actually had it the day *before* I wrote this post and had forgotten (short term memory issues…old age…excuses excuses 🙂 ).
‘A constructible type deriving from DbContext could not be found in the selected file’.
This was misleading because like Ethan, the fact that I was deriving from BaseContext led me to believe that *this* was the cause for not being able to find the DbContext type. But changing CustomerServiceContext to inherit DbContext directly did not fix my problem.
I found this StackOverflow thread about this error message with a response from Brice Lambson of the EF team that suggested an Visual Studio extension was the issue. I had just added two extensions for spell checking my code and comments. One was HTML Spell Checker (from Microsoft), the other was Multi Language Spell Checker (also from someone at Microsoft). So I thought I would disable one at a time to see if one was the culprit. I happened to pick HTML Spell Checker to disable first and voila, the View Entity Data Model tool worked again (after a VS restart). Fortunately the second extension is the one I had really wanted anyway. I believe that this problem will be resolved by the time we get the tools integration in EF6.
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!
OK, getting ‘A constructible type deriving from DbContext could not be found in the selected file’. Which I don’t get. The context I am trying to map derives from my BaseContext and Base Context derives from Dbcontext.
Oh my gosh, I had that just yesterday. I can’t believe I didn’t add it in. Can you believe it was from a Visual Studio Extension I had added. When I disabled the extension, the problem went away. The extension was HTML Spell Checker. I was able to realize this after reading Brice’s (he’s on the EF team) reply in this SO thread: stackoverflow.com/…/a-constructible
So did you just disable extension one by one until you found the problem?
haha. No I had only just installed two so the first one I disabled did the trick. I’m still suspicious though. I don’t like coincidences like this. Was it that particular extension or something about *installing* extensions?
Its extensions in general. I cant enable any extensions and get it to work.
OK. Now that I got it working, totally indispensable.
@Ethan: awesome, and …right? I can’t live without this tool!
I was having trouble getting the EF Power Tools Beta 3’s View Entity Data Model (Read-Only) feature to work in with VS2010. I resolved the "constructible type deriving from dbcontext could not be found in the selected file" error by disabling all other VS extensions. Then I started getting the errors like "Could not find schema information for the element ‘entityFramework’.". It turns out that EF PT beta3 installs EntityFramework.dll version 6.0.0 into your empty project when you do a reverse engineer code first from the DB. When you later try to View Entity Data Model (Read-Only) for a DBContext, the read only EDMX file is built using the schema for EDMX version 3 which is compatible with VS2012 but not VS2010. I used NuGet to replace Entity Framework 6.0.0 in my project with the latest stable version (4.4.0). Now the temporary EDMX file is created using schema version 2, which works with VS2010. Hope this helps others who are still on VS2010.
PS – learned about this tool in one of Julie’s great Pluralsight courses – using EF in Enterprise Applications. Great stuff!
First of all… Awesome information Julie. Being following you since i found about your EF courses on Pluralsight. Second… What if I tell you that closing VS and deleting .suo files helped me with the "Exception has been thrown by the target of an invocation". I implemented all recommendations to DbContexts and whenever I change my model and try to view the EDMX this message is shown.
Haven’t tested but maybe the suo files deletion aren’t needed. Just for you guys to know about it.
I'm having this problem in VS2013 with EF Powertools beta4. I have tried disabling extensions, but nohing makes this issue go away?
Dave, which problem are you having? I'm using the beta4 tools successfully.
I created an MVC 5 application and then used EF 6.1 code first with an existing DB on SQL Server Express. When I try to create the views I’m using the “New scaffolded item…” then selecting the “MVC 5 controller with views, using Entity Framework.” I select the model and context classes and click OK. Then the following error message appears and no code is created. I’ve uninstalled EF Power Tools with the same error.
Error
There was an error running the selected code generator:
‘Exception has been thrown by the target of an invocation.’
Any other ideas about what might cause this error?
Hi Tony,
I am having exactly the same issue. Were you able to fix this?
I am running Visual Studio 2013 with update 2.
@Koen & Tony: FWIW, I’m seeing similar reports of the scaffolding problem on stackoverflow (e.g. http://stackoverflow.com/questions/23576294/application-cant-scaffold-items). Not sure if it’s an EF issue or an issue with some expectation of the scaffolding template. I’ve asked on twitter if anyone is familiar and will report back here.
@Koen, I’m still having the problem. It’s really disappointing as I like the features.
I can’t duplicate the problem. Just out of curiosity, have you tried using the new EF6.1 designer that now let’s you reverse engineer existing db to code first (http://thedatafarm.wpengine.com/data-access/first-look-at-beta-of-ef-6-1-designer/) instead of using the power tools to do that? (And then seeing what happens with the scaffolding?)
I just tried the EF 6.1 and it worked as well.
Thank You.
No I haven’t tried the EF 6.1 designer. I did manage to get the scaffolding to work by commenting out the code inside the OnModelCreating() function per the SO helpers.
Thanks for all the help.
Great to hear, Tony. Although IMHO that hack shouldn’t be necessary. Seems that the scaffold just doesn’t understand fluent configs. My guess (no time to experiment right now) is that it’s not that the context was created by the power tool, but that the existence of the fluent configuration code was creating the conflict. Did you have to use the same workaround with the EF6.1 designer created context?
I am using VS2013 now and am not able to find EF Power Tools to install anymore. I used to use it all the time. What is the best way to make an Entity Data Model diagram now?
Hi Thomas,
It’s still there: http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d.
I sometimes have a hard time finding it from the VS extension manager, myself. You have to type Entity Framework Power Tools with all of the appropriate spaces.
Bless you! I was looking under Packages, *not* Extensions/Updates. Thank you, thank you!
— And still loving your books!
I have been unable to get around this error with Power Tools and I would really like to be able to view my data model.
Error Message: A constructible type deriving from DbContext could not be found in the selected file.
I have read, here in this thread and some others, that this error may be related to VS Extensions and disabling some may resolve the issue. Many of the current extensions in VS cannot be disabled. Says in description “You need to use the Programs and Features pane in the Windows Control Panel to remove this extension.” However, I am unable to see these in the Control Panel. I found a post on StackOverflow that suggests to disable in PowerShell. Since my only experience with PowerShell has been limited to using it within the Package Console for testing some Code First Migrations, I thought I would seek some advice before I cause more issues.
Extensions currently in VS:
These are the items listed in Extension and Updates:
Behaviors SDK (XAML)
Entity Framework Power Tools Beta 4
Microsoft Advertising pubCenter Service for Visual Studio
Microsoft Advertising SDK for Windows 8.1
Microsoft Advertising SDK for Windows Phone 8.1 XAML
Microsoft ASP.NET and Web Tools
Microsoft Visual Studio ASP.Net MVC 5 Scaffolding
NuGet Package Manager for Visual Studio 2013
Visual F# 3.1
Visual Studio Extensions for Windows Library for JavaScript
Windows Phone 8.1 SDK Integration
Workflow Manager Activities
I am using VS Premium 2013
EF 6.1.1
EF Power Tools Beta 4
Any suggestions?
Hey jolco, I really don’t know. I would bet that if you left a comment about your problem in this old workitem, then Brice or one of the other EF team devs who work on this might be able to give you a clue. Sorry I can’t be more help.
http://entityframework.codeplex.com/workitem/810
Julie
Will do. Thanks for the link Julie.
Julie,
I’ve created a sample solution to narrow this down…
I’m working on a solution with several bounded contexts, as you’ve described them.
I have my entities in separate projects from their models.
In my solution, I have:
Foo – entities
Foo.Model – references Foo, Entity Framework
– FooContext : DbContext
Bar – entities
Bar.Model – references Bar, Entity Framework
– BarContext : DbContext
Startup
– App.config
When I first start Visual Studio (2012/2013), the first DB context that I choose to view the entity data model (read-only) from code-first does so successfully. Any DB context afterward fails to view the entity data model (read-only) and I get a error message box that displays “Could not find file or assembly ‘[respective entities project name], Version 1.0.0.0, Culture-neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified.” I have to restart Visual Studio to get EF Power Tools to view the other entity data model (read-only), which is really inconvenient.
Also, curiously, if the DB context that fails to view the entity data model (read-only) is an IdentityContext, I don’t get an error dialog, but a note in the output: “A constructible type deriving from DbContext could not be found in the selected file.”
If I move the entities into the model project, all is well, but now my entities are not agnostic of Entity Framework.
I have all extensions disabled that I can disable. I’m working with EF 6.1.1 and EF Power Tools Beta 4.
Have you experienced this? Is there a workaround that doesn’t compromise my solution design? Did I dig myself an unnecessary hole?
I’ve scoured the internet for a working solution.
Hey Matt,
yikes, not sure off the top of my head on this one. I’ve never been forced to move my domain classes into the same project as my context for using this tool. I have this setup frequently. I think you’re going to need someone to look at it with you. Also, deep apologies for missing your comment. I know it’s been 3 weeks so hopefully you’ve got it solved already and I’d be interested in knowing what the problem & solution were.
I just spent a couple of hours trying to get rid of the “Exception has been thrown by the target of an invocation” popup when trying to view the model of my Code First context. All the references and connection strings seemed right.
Turned out that in my App.config file I had:
[entityFramework codeConfigurationType=”MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6″]
Which I added trying to debug something else and did not remove. When replaced with the normal [entityFramework] without parameters it worked!
I hope it can help someone else from losing a couple of hours!
The view entity data model is not working with IdentityDbContext, I’m getting a message about nameOrConnectionString can’t be empty. Is this a known bug?
Thanks!!
Hi Julie,
The screendumps seem down – can you please update? Thanks in advance.
Regards,
/P
whoa! thanks. moved the blog (over a year ago) and some of the redirects just aren’t working. Thanks for pointing this one out.
Hi Julie, just wanted to warn about a Visual Studio plugin that broke EF Power Tools. It’s
a little vsix called PropMan. After removal everything worked back as normal. (2015) Just wanted to drop this here in case somebody runs into the infamous “Exception has been thrown by the target of an invocation” problem whilest having this tool installed.
Thanks for your pointers Julie! It pointed me right at the problem – CodeFirst + PowerTools + resolving connection strings (VS2015)
internal class MyContext : DbContext
{
//Both Migrations and EF PowerTools were okay with this…
public MyContext() : base(“name=MyConnStringName”)
//Migrations was okay with this, but EF PowerTools Throws “object reference not set to an instance of an object” in a dialog box… Very confusing :s
public MyContext() : base(ConfigurationManager.ConnectionStrings[“ConfigMgr”].ConnectionString)
Hi, Is there a version that works for EF Core? I get an error with EF Core.
oh yes yes! EF Core Power Tools is here :https://github.com/ErikEJ/SqlCeToolbox/wiki/EF-Core-Power-Tools
You can find them via VS2017 extensions as well. Erik has taken over managing the EF6 power tools also here: https://github.com/ErikEJ/EntityFramework6PowerTools
Hey,
It still happens in VS 2019.
Was following Julie’s Course.
Thanks For the Fix!!!!
How did you fix this issue?