스캐 폴딩 컨트롤러가 Visual Studio 2013 업데이트 2에서 작동하지 않습니다.
문제:
Visual Studio 2013 업데이트 2로 업데이트했는데 이제 컨트롤러를 스캐 폴드 할 수 없습니다.
문제는 특정 프로젝트가 아닙니다. 컨트롤러를 스캐 폴드하려고 할 때 ALL 및 ANY 프로젝트에서 다음 오류가 발생합니다.
There was an error running the selected code generator:
'Exception has been thrown by the target of an invocation.'
Visual Studio 2013 업데이트 2로 업데이트하기 전에 작동했습니다.
문제를 검색해 보았지만 다양한 제안이 작동하지 않습니다.
예 :
내 컨텍스트에서 OnModelCreating을 주석 처리합니다.
MvcScaffolding 등과 같은 패키지 제거 (설치된 것이없고 어떤 프로젝트에서도 작동하지 않음)
일부 템플릿을 수정 / 사용자 정의했지만 변경 후 작동했습니다.
편집하다:
Visual Studio 2013 업데이트 2를 제거하여 Visual Studio 버전 12.0.21005.1 REL로 되돌 렸습니다.
문제가 사라졌습니다. 따라서 문제는 업데이트 2에서 확실히 발생합니다.
질문:
누구나 (Microsoft 포함) 수정 사항을 알고 있습니까?
편집 2 :
Farruk Subhani의 답변은 질문을 해결하지 못합니다.이 질문은 MVCScaffolding에 대한 참조를 제거해도 문제가 해결되지 않는다는 것을 명확하게 설명합니다.
200 포인트 현상금을 추가했습니다. 명확하게 설명 된대로 질문에 답해주세요.
아무것도 작동하지 않는 여러분 모두에게 진정한 대답은 web.config에 configSource가 있고 연결 문자열이 인라인되어야하는 모든 것을 제거해야한다는 것입니다.
편집하다:
사람은 오직 할 필요가 있다고 지적 <configSettings>
, <appSettings>
및 <connectionStrings>
태그가 configSource 속성을 사용하지. 그리고 그는 rewriter 태그와 같은 다른 곳에서도 configSource 속성을 사용할 수있었습니다.
도구가 연결 문자열 및 응용 프로그램 설정과 같이 사용하는 항목에 대해 configSource 위치를 따를 수 없다고 생각합니다.
아직 해결되지 않은 경우 Microsoft에서이 문제를 해결해야합니다.
편집 2 :
@awrigley가 그의 대답을 올바른 것으로 표시했다고 생각하더라도 이는 알려진 Visual Studio 버그입니다. 나는 그때 말하고 곧 관심을 끌 것이라고 생각합니다. https://github.com/aspnet/Tooling/issues/169#issuecomment-144197015
여러 가지가 저에게 효과적이었습니다.
Visual Studio 2013 업데이트 3으로 업그레이드합니다.
Entity Framework를 6.1.1로 업그레이드
DbSet <...> 대신 IDbSet <...>을 사용하도록 컨텍스트 구성을 수정합니다 (비동기 작업 사용에 영향을 미칠 수 있다고 들었지만 로그인 작업 등에서 사용하므로 내 경우에는 분명히 그렇지 않습니다. ASP.NET Identity 2 샘플 Nuget 패키지에서 제공).
이 조합이 작동하는 이유는 모르겠습니다. 그러나 MS의 엄청난 침묵을 감안할 때 나는 아마도 혼자가 아닐 것입니다. 업데이트 2가 작동하지 않은 것 같습니다 ...
해결책
섹션 확인
<connectionStrings>..</connectionStrings>
이후
<configSections>..</configSections>
패키지 관리자 콘솔 에서 다음 명령을 실행하십시오 .
Uninstall-Package EntityFramework -Force
Install-Package EntityFramework
Uninstall-Package MvcScaffolding
Install-Package MvcScaffolding
Visual Studio 2013 업데이트 3에서도 똑같은 문제가 발생했지만 Entity Framework로 작업하는 스캐 폴더에만 해당됩니다. 이 문제는 Entity Framework 6.1.0과 Visual Studio 2013 업데이트 2 이상의 스캐 폴더 간의 비 호환성으로 인해 발생하는 것 같습니다.
EF를 업그레이드하려면 다음을 수행하십시오.
패키지 제거 EntityFramework -Force
설치 패키지 EntityFramework
업그레이드 후 비계가 잘 작동합니다. Entity Framework가 필요한 모든 프로젝트에 새 버전을 설치해야합니다.
제 경우에는 web.config의 연결 문자열 문제를 해결했습니다.
내가 가진 문제 이전
<connectionStrings configSource="Configs\ConnectionString.config"/>
왜 그런지 모르겠지만 대 데이터베이스에 연결할 수 없으며 실패합니다.
변경 후
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
그리고 그것은 작동합니다
누구나 이해할 수 있도록 영어로 조금 더 설명하겠습니다. 이것이 누구에게나 도움이되기를 바랍니다. 이것은 Visual Studio가 데이터베이스 모델에 연결하지 못하기 때문에 발생합니다.
이는 DbContext를 확장하는 클래스의 이름 및 / 또는 경로를 변경하고 Web.config 파일 (프로젝트의 가장 바깥 쪽 부분 : 루트)에서 변경하지 않은 경우에 발생합니다.
예:
DbContext 코드를 스캐 폴드했다고 상상해보십시오.
a) 프로젝트에서 폴더를 마우스 오른쪽 버튼으로 클릭하고 "ADO.NET Entity Data Model"을 추가하고 이름을 "Model1"로 지정했습니다.
다음 코드를 얻습니다.
public class Model1 : DbContext
{
// Your context has been configured to use a 'Model1' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'Skelleton.Models.Model1' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'Model1'
// connection string in the application configuration file.
public Model1()
: base("name=Model1")
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
b) 이제 방금 작성한 이름이 잘못되었다고 판단 했으므로 AppContext로 변경합니다.
이제 코드는 다음과 같습니다.
public class AppContext : DbContext
{
// Your context has been configured to use a 'AppContext' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'Skelleton.Models.AppContext' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'AppContext'
// connection string in the application configuration file.
public AppContext()
: base("name=AppContext")
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
그런 다음 뷰를 사용하여 CRUD (만들기, 읽기, 업데이트, 삭제) 작업을 스캐 폴딩하려고 시도했지만 실패합니다!
왜 그런 겁니까?
web.config 파일로 이동하면 다음 문자열을 볼 수 있습니다.
<add name="Model1" connectionString="data source=(LocalDb)\v11.0;initial catalog=Skelleton.Models.Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
(이 줄은 일반적으로 아래에 있습니다. <add name="DefaultConnection"
)
그리고 문제가있는 곳이 있습니다. 지정한 이름으로 Model1을 변경해야합니다!
이 경우 "Model1"대신 "AppContext"라고 표시되어야합니다.
그리고 그것이 말하는 곳 :
initial catalog=Skelleton.Models.Model1;
다음 사항을 확인하십시오.
클래스가있는 .cs 파일의 이름입니다.
네임 스페이스 (또는 클래스 이름 앞에 오는 일련의 이름 (점으로 구분))이 올바른 것입니다. ".cs"확장자의 끝에 추가하지 않는 것이 중요합니다. 파일의 이름입니다.
다음과 같이 표시되어야합니다.
내부 및 외부 (내부 및 파일 이름)에서 클래스 이름을 변경하고 위치를 변경 하지 않았기 때문에 이름을 AppContext로 변경했습니다.
이것이 완료된 후. 당신은 정상적으로 비계 할 수 있습니다;)
도움이 되었기를 바랍니다!
나를 위해, 내가 확인했다 <configSettings>
, <appSettings>
, <connectionStrings>
태그 된 NOT 사용하여 configSource
속성을.
태그 configSource
와 같은 다른 곳에서는 여전히 속성 을 사용할 수있었습니다 rewriter
.
문제는 web.config 파일의 잘못된 구성 때문이라고 생각합니다.
In my case I had multiple <entityFramework>
sections in web.config, and the problem resolved after I changed the configurations.
I'm on VS 2013 Update 4 and have exactly same issue. It works for me when moving connection string from external file into web.config. So I guess you could try to make sure not using configureSource attribute for connectionString when scaffolding.
My web.config before and after the change Before:
<connectionStrings configureSource="connectionStrings.config/>
After:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net configSource="log4net.config" />
<connectionStrings>
<clear/>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=YourDb;Integrated Security=False;User ID=sa;Password=YourPassword!#;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
This can be useful for people who haven't installed any scaffolding nuget packages in their solution.
In fact I don't have mvcscaffolding or t4scaffolding installed and got the same error message.
In my case the problem/bug was caused by changing the connection string.
Here what I had/steps to reproduce.
- Installed Visual Studio 2013 Community Edition
- Created MVC project
- Created code first model
Edited connection string to connect to a real server, like this:
<add name="DefaultConnection" connectionString="server=myserv;database=MyCustomerDB;user id=myuser;password=mypass" providerName="System.Data.SqlClient" />
Then I enabled migrations via nuget, like this:
- Enable-Migrations
- Add-Migration InitialCreate
- Update-Database
- I started the website and I could register a user. All tables were created correctly.
Then I created a controller by using the scaffolding option:
- right click on "Controllers" > "Add" > Controller... > MVC 5 Controller with views, using Entity Framework > selected my context and a class to be used. It worked.
Then I decided to do more code first changes and begin from scratch:
I changed the connection string as follows, to use localdb:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Test-20141126094523.mdf;Initial Catalog=aspnet-Test-20141126094523;Integrated Security=True" providerName="System.Data.SqlClient" />
Then I went on:
- deleted the migrations folder
- re-enabled migrations using the same commands as above, in the nuget console
- started thw website and registered a user
- checked the mdf db. All tables are there, so the connection string works.
- right click on "Controllers" > "Add" > Controller... > MVC 5 Controller with views, using Entity Framework. Selected my context and a class to be used. It did not work and this popup error appeared:
There was an error running the selected code generator: 'Exception has been thrown by the target of an invocation.'
SOLUTION:
After some investigation, what I did, is changing back the connection string in the web.config
to the initial one to the "real server" (instead of localdb). I tried again to generate the controller with views. It worked!
So it seems to me a connection string problem/bug or a localdb problem... can't explain it. Maybe Visual Studio doesn't like what I did, I had to keep my old connection string...
Anyway, so now when I need scaffolding I just change the connection string to the one that works. Then to test my website I change it back to the localdb one.
I have performed following to solve this issue:
- In Package Manager check if you have MVCScffolding or T4Scaffolding (Core or pre release for vs2013)
- Uninstall all packaged that depend on any of MVCScaffolding or T4Scaffolding
- Copy CodeTemplates Folder in full (Do not replace your custom templates but make sure you have rest of the files from root of this folder. I take that you have done that part as you have customised some templates so you know where this folder is)
- Build Your project and close it.
- Restart Visual Studio under admin mode
- Open Package Manager Console (it should not have any errors and you can see PM> without errors.
- Right Click on Controller folder and choose Add->New Scaffolding Item or Choose Add->Controller both should ask which one you want and then choose MVC5 scaffold or which ever appears in list.
- You will then get to select your parameters if its controller you might need to choose DBContext or repository etc.
This produced the controller and relevant views for me.
I added a custom partial view called QuickView in that folder however this scaffolding procedure did not consider that and only generated views that it was doing by default. I am not sure if you need to add these custom views in a file to tell Scaffolder to generate those as well.
For me what worked was to make sure the <configSections>
node in the web.config file was the first node immediately after <configuration>
node.
Initially, when I added my connectionStrings
, I had actually placed it before the configSections
, which made the Scaffold tool break.
Seems like when the scaffolding runs and tries to grab connection info, it expects the config section for the entityFramework node to be there already so it know what DB provider to use, but when I had the connection string before configSections, it didn't know to use LocalDB (which is what my conn string was using).
I'm running VS 2015RC the last one before final cut. Not to discount any of the solutions here. My solution was under nugget package manager and updated my Microsoft.Aspnet.Mvc 5.2.3 package and that fix my issue. I hope that helps anyone using VS 2015.
i used Initializer and when remove/comment Initializer from myDbContext constructer , scaffolding work fine
public myDbContext () : base("name=DefaultConnection")
{
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DastanakDbContext>());
//Database.Initialize(true);
}
업데이트 4에서도 이와 동일한 문제가 발생했습니다 <configSections></configSections>
. 섹션 이름이 정의되지 않았기 때문에 문제가 발생한 것으로 나타났습니다 . 태그 사이에 넣은 수정 사항은 다음과 같으며 모든 오류가 수정되었습니다.
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
프로젝트를 빌드하면 모든 것이 작동합니다. 건배!
'Development Tip' 카테고리의 다른 글
C ++ 용 '즉시 사용 가능한'2D / 3D 플로팅 라이브러리가 있습니까? (0) | 2020.11.18 |
---|---|
__init__.py 사용 (0) | 2020.11.18 |
React.js ES6는 'this'를 모든 메소드에 바인딩하지 않습니다. (0) | 2020.11.18 |
C ++의 가비지 컬렉션 라이브러리 (0) | 2020.11.18 |
Haskell의 Stream Fusion이란? (0) | 2020.11.18 |