Application can't scaffold items

隐身守侯 提交于 2019-12-17 07:16:10

问题


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?


回答1:


I had this problem too, I solved the problem by calling the base.onModelCreating in my DB context

base.OnModelCreating(modelBuilder);



回答2:


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.




回答3:


This solved the issue for me,

Adding throwIfV1Schema: false to base of DbContext

As so:

public MyDbContext() : base("ConectionStringName", throwIfV1Schema: false) { }



回答4:


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.




回答5:


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.




回答6:


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.)




回答7:


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") { }



回答8:


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.




回答9:


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>();



回答10:


I tried most of the above without luck.

What finally worked was:

  1. Delete the previously dynamically created string entry
  2. Delete my model (keeping all controllers and views)
  3. 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.

  1. 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.




回答11:


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




回答12:


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!




回答13:


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.




回答14:


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.




回答15:


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.




回答16:


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




回答17:


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.




回答18:


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 :-( )




回答19:


I Had the same error. Here are the two things I did to fix the problem:

  1. Added name to base in my context: base("name=connectionstringname")
  2. I made a mistake in myconnection string and fixed it.



回答20:


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.




回答21:


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>



回答22:


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...

  1. Moved the connection string out of the Web.config file
  2. Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config
  3. 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 ...

  1. Put the complete connection string back in Web.config AND remove the reference to the external connection string file
  2. Add a parameterless constructor to my context class and give it the name of my connectionString like this: public contextClass() : base("name=connectionStringName") { }

  3. Rebuild the solution, and create the controller again, and it worked!




回答23:


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.




回答24:


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>



回答25:


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>



回答26:


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.




回答27:


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.




回答28:


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; }
    }
}



回答29:


EF 6.1 does not Support scaffolding template use EF 5 Chares



来源:https://stackoverflow.com/questions/23576294/application-cant-scaffold-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!