I created an MVC 5 application in VS 2013 Professional 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.’
I've also tried uninstalling/reinstalling VS 2013 and SQL Server with no changes.
Any other ideas about what might cause this error?
In my case I moved my connection strings out of the Web.config to
<connectionStrings configSource="ConnectionStrings.config"/>
that when I started getting the error when I was trying to scaffold.
There was an error running the selected code generator: ‘Exception has been thrown by the target of an invocation.’
Moving my connection strings back to the Web.config solved my issue.
I had this problem too,
I solved the problem by calling the base.onModelCreating in my DB context
base.OnModelCreating(modelBuilder);
I had faced the same problem while creating controller using scaffold with 'ASP.NET MVC5 using views with Entity Framework'
The problem was because I provided <connectionStrings> tag before <configSections> in web.config. setting <connectionStrings> after <configSections> resolved the issue.
I guess, while scaffolding, ASP.NET MVC want to resolve the Entity Framework first, then the connection string, as I have provided connection string earlier so that after resolving the Entity Framework version it could not find the connection string so it thrown invocation problem.
This solved the issue for me,
Adding throwIfV1Schema: false to base of DbContext
As so:
public MyDbContext() : base("ConectionStringName", throwIfV1Schema: false) { }
Late reply; but, I am posting this answers with the hope that somebody can use this answer to solve their problem.
For some reason, if your program CANNOT read connectionString information (either from web.config or from other means) then, this error will be thrown.
Make sure that valid connectionString information is being retrieved properly without any problem.
I had the same error message.
I tried adding a new Data context class from the Add Controller dialog, and then I got a different error:
There was an error running the selected code generator:
'Sections must only appear once per config file. See the help topic
<locations> for exceptions.
It turns out that I had two <connectionStrings> elements in my web.config file. (I had pasted one from the app.config of the class library that contained my Entity Framework model.)
In my case, I had to revert my DBContext constructor to just using a static connection string, as defined in web.config
Scaffolding did not work when I used a dynamically created connection string.
public MyContext() : base("name=MyContext") { }
I had the same problem where it wouldn't add scaffold items it seems that uninstalling entity-framework through the nuget package manager console works
To Run Package Manager Console :
Tools -> NuGet Package Manager -> Package Manager Console
To Remove:
UnInstall-Package EntityFramework
To Reinstall:
Install-Package EntityFramework
Or in one command:
Update-Package -reinstall EntityFramework
I hope this can help someone as it took me a while to come to this.
This may help resolve your error.
In my OnModelCreating i was doing this for each entity:
modelBuilder.Configurations.Add(new EntityTypeConfiguration<EntityModel>);
When i changed it to the following i stopped getting the error you are receiving.
modelBuilder.Entity<EntityModel>();
I tried most of the above without luck.
What finally worked was:
Delete the previously dynamically created string entry
Delete my model (keeping all controllers and views)
Recreate the ADO.NET Entity Data Model - using the same name, creating a new connection string entry with the same name as before
Then everything worked again, minus 3 hours of development time.
re-add (from a backup) all of my property attributes to the table/entity classes
Seems to have something to do with the dynamically created connection string and the model. Would appreciate any thoughts on what could have happened.
In my case, I solved the issue with the connection string in the web.config.
Previuos the issue I has
<connectionStrings configSource="Configs\ConnectionString.config"/>
and I doesnt know why, but vs cant connect to the database and fail.
after the change
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
and it works
My solution was as simple as changing back the connection string name in my Web Config to DefaultConnection. Even though my dbContext has another name!
Took me 2 hours to find out this nonsense!
It seems a problem of connecting setting / inconsistent entry in via Web.config.
To fix this issue , follow below steps:
Remove connection related information (staring with <connectionStrings> from Web.config and remove models generated so far.
Now generate the model and it will add fresh connection entry in Web.config file. Once model is generated, build the solution then start doing Scaffolding controlled. it will work.
I ran into this problem too using VS 2015. I tried all the other solutions here to no success. It turned out that my connection string (although formed exactly how MS tells us to form it) needed double \ to work properly.
Here is what it was that was NOT working:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
and here is what I changed it to in order to get the code generator to work:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
Notice the double \ characters in front of V11.0 and the database name.
Hope this saves somebody else some time.
UPDATE
This gets the code generation to work, but then the app won't run because the \V11.0 isn't a valid connection string. This looks to me like MS has a bug in their code generation when it parses the connection string. I had to change it back to a single \ after I ran the code generation to get the app working again.
UPDATE 2
After some more digging by my partner, we found out that what was really screwing up code generation was the fact that we had changed the "Initial Catalog" field. When the project was created by the Wizard, it automatically set the Initial Catalog to aspnet--. We had then changed this Initial Catalog field to be DB. This worked great for the application running. It could get to the database just fine. But for some reason this screws up the code scaffolding generation. By putting the Initial Catalog back to what it was before (the aspnet--, the scaffolding started to work again (without needing the \V11.0).
Hope that helps somebody in the future.
Check relationships between entities or other model design problem. For testing, create new class model without no relationship and use Scaffold to generate controllers and views.
Works for me.
I was getting the same error when I made some changes to my model .. Only way I was able to resolve was
1) stop/kill the process
2) clean solution and rebuild the solution
If by any chance you are following "Getting Started with Entity Framework 6 Code First using MVC 5" by Tom Dykstra.
I doubled check everything and my connection string is perfect. What I failed to realize was I copied another set of appSettings which I already have. Look below
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
My advice is to check every inch of Web.config and I'm sure that is the culprit.
In my case NuGet added the following provider to the web.config:
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact"/>
When I changed the provider to
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
It solved the problem (costed me about 5 hours though to figure it out :-( )
I Had the same error. Here are the two things I did to fix the problem:
Added name to base in my context:
base("name=connectionstringname")
I made a mistake in myconnection string and fixed it.
It is (I'm 99% positive) a connection string issue. Once i fixed the issue in Web.Config the error went away. I was using DB first, in another project and once I copied the DB first connection string from the App.config into the web.config (using the same name) it worked as expected.
Using Visual Studio 2015
Upgraded mysql server and in the process the mysql for visual studios was upgraded from 6.9.7 to 6.9.8
In my web config there was still a reference to the old 6.9.7 version
Here is my git diff that solved the issue:
- <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.7.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
+ <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.8.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
I realize this question is old now, but I thought I'd post what solved my issue in case it helps anyone later on. In my case, it was a combination of several things mentioned in other answers. To secure my connection string I had...
Moved the connection string out of the Web.config file
Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config
Used a SqlConnectionStringBuilder to put the elements together and then pass it to my context class constructor
After doing this, I was unable to create any more controllers. To fix the issue, I had to ...
Put the complete connection string back in Web.config AND remove the reference to the external connection string file
Add a parameterless constructor to my context class and give it the name of my connectionString like this:
public contextClass() : base("name=connectionStringName") { }
Rebuild the solution, and create the controller again, and it worked!
everyone. I know I'm a little late, but I think that is still valid to share my experience with this problem.
I faced this message in two projects and in both cases the problem was with the connection string.
In the first case it was "InitialCatalog" instead of "Initial Catalog" (separated).
In the second case the server name (Data Source param) was wrong.
I hope it helps.
Best regards.
For some reason when I comment the oracle.manageddataaccess.client section out between <configSections> in web.config, it worked. (VS 2015 and ODT 12)
<configSections>
<section name="entityFramework" type" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!--<section name="oracle.manageddataaccess.client" />-->
</configSections>
In my case, the problem was caused by an external app settings file:
<appSettings configSource="appSettings.config" />
Bringing the app settings back into the web.config file resolved the issue.
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
I had this:
<appSettings configSource="App_Config\Server\AppSettings.config" />
<connectionStrings configSource="bin\Connections.config" />
I had to remove BOTH AND put back.
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
Removing just still caused the same error.
Using: VS 2015 Community Edition and EF 6.1.3
Implemented also: Seed method, with a personalized class, and configured in the web.config file to run every time that the model changes.
This seems to be related to some misconfiguration in the web.config file, in my case, like some of the cases I see in this post with other sections of the file, the section was repeated with different content, but it's repeated the main tag of course. The case of the section out of place, over the section, is also cause of the same behavior and narrow message while try to scaffold.
Your context class might be throwing an exception.
I was following along in the book "C# 6.0 and the .NET 4.6 Framework" and one of the last exercises of the data access layer section was to add logging. Well, I guess that blows up the scaffold wizard. Probably file permissions on sqllog.txt or HttpRuntime is not defined...who knows. When I commented all this stuff out, it worked again.
namespace AutoLotDAL.EF
{
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using AutoLotDAL.Interception;
using AutoLotDAL.Models;
using System;
using System.Data.Entity.Core.Objects;
using System.Web;
public class AutoLotEntities : DbContext
{
//static readonly DatabaseLogger databaseLogger =
// new DatabaseLogger($"{HttpRuntime.AppDomainAppPath}/sqllog.txt", true);
public AutoLotEntities()
: base("name=AutoLotConnection")
{
////DbInterception.Add(new ConsoleWriterInterceptor());
//databaseLogger.StartLogging();
//DbInterception.Add(databaseLogger);
//// Interceptor code
//var context = (this as IObjectContextAdapter).ObjectContext;
//context.ObjectMaterialized += OnObjectMaterialized;
//context.SavingChanges += OnSavingChanges;
}
//void OnObjectMaterialized(object sender,
// System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e)
//{
//}
//void OnSavingChanges(object sender, EventArgs eventArgs)
//{
// // Sender is of type ObjectContext. Can get current and original values,
// // and cancel/modify the save operation as desired.
// var context = sender as ObjectContext;
// if (context == null)
// return;
// foreach (ObjectStateEntry item in
// context.ObjectStateManager.GetObjectStateEntries(
// EntityState.Modified | EntityState.Added))
// {
// // Do something important here
// if ((item.Entity as Inventory) != null)
// {
// var entity = (Inventory)item.Entity;
// if (entity.Color == "Red")
// {
// item.RejectPropertyChanges(nameof(entity.Color));
// }
// }
// }
//}
//protected override void Dispose(bool disposing)
//{
// DbInterception.Remove(databaseLogger);
// databaseLogger.StopLogging();
// base.Dispose(disposing);
//}
public virtual DbSet<CreditRisk> CreditRisks { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Inventory> Inventory { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
}
EF 6.1 does not Support scaffolding template use EF 5
Chares
i have a class library, with domain objects (linq based objects, in .net
4.0).
i want to have this library use connection strings for its own app.config.
there are some problems:
following the model used by Settings : ApplicationSettingsBase, i created a
wrapper that should read the settings from app.config.
however, unlike the model, i provide default values.
the problem is that the properties which should load the data from app.config
internal sealed class ApplicationSettings : ApplicationSettingsBase
{
// other properties
[SpecialSetting( SpecialSetting.ConnectionString )]
[global::System.Configuration.DefaultSettingValueAttribute("Server=.;Database=RFPLUSSTD;User Id=SYSADM;Password=SYSADM;")]
public string MainConnectionString
{
get { return (string)this["MainConnectionString"]; }
}
// other properties
}
in app.config:
<connectionStrings>
<add name="MainConnectionString"
connectionString="..."
providerName="System.Data.SqlClient" />
</connectionStrings>
now, this doesn't work...
i tried to set the name of the conn string to the fully qualified name like
namespace.class.property, but to avail.
i don't want to use the default Settings class, used by the dbml because
it compiles the settings :D and i can't change them without recompiling...
i'm already using a different model of app settings class in a project in
1.1, but i thought 3.5 has grown enough and have its own objects, that
work..
So, why is not working and how can i make it work?
Thank you
You need to make sure that you have permissions in the file system to make the change. I hope you have considered that. If you are sure that you changed the config file and if it only brings the default settings, it might be loading the config file from output bin folder not in the project root. If you are sure that the modification fails, please post the error message.
Updated:
Hi Jack, I think the main issue with your code is that it is creating new instance of the ApplicationSettings class every time and if the setting is in user scope, you will be having null value and then it results to default value every time.
You could easily do it with the built in Settings class. By default the Settings can only be accessed within the Assembly, internal sealed partial class Settings (in Settings.Designer.cs). If you change this to public sealed you will be able to access the Settings from any assembly and the next thing is you have to keep the setting to Application Scope not User scope. Once you have done these two, you can retrieve and save without any problem.
I'm trying to get my key value set in the appsettings.Config file but seems not working.
This is what i wrote for that. The code is called from the constructor of an MDI file and its returning only null value. Anybody know why?
var getValue = ConfigurationSettings.AppSettings["ShowQueryTextbox"];
I also tried with ConfigurationManager.AppSettings . That too didnt work.
My AppSettings Code is as follows.
<configuration>
<appSettings>
<add key="ShowQueryTextbox" value="true"/>
</appSettings>
</configuration>
ConfigurationSettings.AppSettings are obsolete, try
ConfigurationManager.AppSettings["ShowQueryTextbox"];
Remember that to use:
ConfigurationManager.AppSettings["MyKey"];
You need to add reference to System.Configuration to your project.
The issue arise on renaming the App.Config file as AppSettings.Config. Thanks for all the guidances and help.
The ConfigurationManager is still up to date - Year 2017.
Btw, if you simply want to convert the appsettings configuration value from string to bool, then use Convert.ToBoolean
if (Convert.ToBoolean(ConfigurationManager.AppSettings["EnableLoggingInfo"]))
{
log.Info(message);
}
In your appsettings configuration (web.config)
<appSettings>
<add key="EnableLoggingInfo" value="true" />
</appSettings>
I am able to get like this:
System.Configuration.ConfigurationManager.AppSettings.Get("KEY").ToString();
Assuming you have added it to the required config file, Can you check the case of the key you are trying to access it's case sensitive so if you have keyed in a different case, it won't be returning the expected value.
This error can also arise if you have the appsettings in the wrong configuration file - example in a WCF application it should be the one in the hosting project
Check Properties.Settings.Default.ShowQueryTextbox.
I have a solution which has multiple output projects (a website, and admin tool, and a SOAP API layer).
They each share common projects in the solution (the service layer, data layer etc). In one of these common projects, I am looking to store a config layer.
Right now, we have three seperate appsettings config files for each output project -
development.AppSettings.config
testing.AppSettings.config
production.AppSettings.config
So altogether, there are nine config files. Only one is used in each project, as they are referenced by utilising the configSource attribute in the web.config appsettings node.
Anyhoo, it's getting to be a pain any time we want to add/remove values from our config files, because it means that we have to change all nine files to do this. And here's what I'd like to do:
In the common project, we have three config files as above. These would be set to copy to the output directory, so that each project has a copy of them. These would be the 'base' config.
Then in each project, I would like to have three files again, but they wouldn't necessarily have to contain the same values as the base configs. If they did however, then the base config value would be overridden by the value in the output project config. A form of configuration inheritance, I suppose.
On application start, I'd like to be able to get these two config files - the base config, and the project config file. And then set the app settings accordingly.
What I'm wondering though, is what's a nice way of determining which file to use? Also, I'm wondering if this is a good way of sharing application values across a large solution, and if there's another, perhaps more efficient way of doing it?
If I'm in development mode, then I don't want production.appsettings.config, and vice versa if I'm in production mode.
Is there a simple way to get the mode (development/testing/production) that I'm in before I go off and get the configurations?
You can have one set of files (3 configs) and link/share them in whatever projects you need.
http://www.devx.com/vb2themax/Tip/18855
Hope this helps.
You could use the ConfigurationManager.OpenExeConfiguration static method. This will allow you to work with as many config files as you want.
You may also try creating a custom class to store all of your settings. You could then serialize your object to save it as a file. You could extend your base custom config class to fit all your other projects.
After some careful thought, and a trip to the toilet at 03:30, I came across a solution which works.
Let's say that we have some appSettings in our base config file:
<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="MyValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />
And in my output project, I have three appSettings:
<!-- This is used to identify which config to use. -->
<add key="Config" value="Development" />
<!-- Different value to the one in the base -->
<add key="MyKey2" value="NewValue2" />
<!-- This key does not exist in the base config -->
<add key="MyKey6" value="MyValue6" />
In my Application_Start, I have a call to GetConfigs():
ConfigHelper.GetConfig(HostingEnvironment.MapPath("~/bin/BaseConfig"));
And the actual GetConfigs function:
public static void GetConfigs()
{
if (configMode == null)
{
configMode = ConfigurationManager.AppSettings.Get("Config").ToLowerInvariant();
}
//Now load the app settings file and retrieve all the config values.
var config = XElement.Load(#"{0}\AppSettings.{1}.config".FormatWith(directory, configMode))
.Elements("add")
.Select(x => new { Key = x.Attribute("key").Value, Value = x.Attribute("value").Value })
//If the current application instance does not contain this key in the config, then add it.
//This way, we create a form of configuration inheritance.
.Where(x => ConfigurationManager.AppSettings.Get(x.Key) == null);
foreach (var configSetting in config)
{
ConfigurationManager.AppSettings.Set(configSetting.Key, configSetting.Value);
}
}
Now, my output project effectively has the following configuration settings:
<add key="Config" value="Development" />
<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="NewValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />
<add key="MyKey6" value="MyValue6" />
Simples!