Qual é o formato correto para executar a ferramenta Migrate.exe do Entity Framework sem um Web/App.config?
-
14-12-2019 - |
Pergunta
Recentemente, mudamos para migrações de dados do Entity Framework e estou trabalhando em alguns scripts de automação de construção para nosso aplicativo MVC.Posso executar com êxito as migrações de nosso servidor de compilação usando a ferramenta Migrate.exe em 4.3 se eu tiver um Web.config para apontar. O comando se parece com:
ProjectName\packages\EntityFramework.4.3.1\tools\migrate.exe MyAssembly
/startupdirectory:ProjectName\bin\Debug
/startupconfigurationfile:ProjectName\Web.config
/verbose
No entanto, por vários motivos, gostaria de evitar o uso do Web.config e apenas passar a string de conexão correta no momento da migração:
ProjectName\packages\EntityFramework.4.3.1\tools\migrate.exe MyAssembly
/startupdirectory:ProjectName\bin\Debug
/connectionString:"Data Source=awesomeserver;Initial Catalog=awesomedatabase;User Id=funkyuser;Password=crazypassword"
/verbose
Isso não funciona.Pior ainda, ele trava o Migrate.exe com uma NullReferenceException.A string de conexão é idêntica àquela que usamos em nosso Web.config.
Alguém já encontrou isso antes?O formato da minha string de conexão está errado?Erro?
Solução
Ok, nós descobrimos.Ao executar sem o Web.config, o parâmetro connectionProviderName também deve ser passado em:
ProjectName\packages\EntityFramework.4.3.1\tools\migrate.exe MyAssembly
/startupdirectory:ProjectName\bin\Debug
/connectionProviderName:"System.Data.SqlClient"
/connectionString:"Data Source=awesomeserver;Initial Catalog=awesomedatabase;User Id=funkyuser;Password=crazypassword"
/verbose
Eu confirmei que isso funciona.
Outras dicas
Ainda não encontrei uma solução que realmente funcione sem especificar o arquivo web/app.config.Veja abaixo.
No entanto, se você puder aceitar fornecer um web/app.config e substituir a cadeia de conexão como parâmetros de linha de comando, o seguinte funcionará com o nuget do Entity Framework 5.0 e o .NET 4.5.Também deve funcionar para .NET 4.0 com o soluções alternativas documentadas.
Exemplo de estrutura de pastas:
trunk\MySolution.sln
trunk\run_migration.bat
trunk\MyMvc4App\MyMvc4App.csproj
trunk\MyMvc4App\web.config
trunk\MyMvc4App\bin\MyMvc4App.dll
trunk\MyMvc4App\bin\EntityFramework.dll
trunk\packages\EntityFramework.5.0.0\tools\migrate.exe
run_migration.bat:
SET AssemblyName=MyMvc4App
SET StartUpDirectory=MyMvc4App\bin\
SET ConnectionString=Server=tcp:XXXX.database.windows.net,1433;Database=XXXX;User ID=XXXX;Password=XXXX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;MultipleActiveResultSets=True
SET ConnectionStringProvider=System.Data.SqlClient
SET ConfigFilePath=%CD%\MyMvc4App\web.config
SET MigrateExe=packages\EntityFramework.5.0.0\tools\migrate.exe
%MigrateExe% %AssemblyName%.dll /startUpDirectory:%StartUpDirectory% /startUpConfigurationFile:"%ConfigFilePath%" /connectionProviderName:"%ConnectionStringProvider%" /connectionString:"%ConnectionString%" /verbose
pause
Fim da solução.
Omitindo o arquivo de configuração:
Ao tentar omitir o arquivo de configuração, sempre recebia a seguinte exceção, não importa o que tentasse.Não experimentei o EF 4.3, então suspeito que o comportamento mudou entre 4.3 e 5.0.
System.Data.Entity.Migrations.Design.ToolingException: Exception has been thrown by the target of an invocation.
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.Console.Program.Run()
at System.Data.Entity.Migrations.Console.Program.Main(String[] args)
ERROR: Exception has been thrown by the target of an invocation.