3
respostas

Erro : Entity.Migration..... threw an exception.

Boa noite. Mesmo com respostas no fórum e pesquisa na web sobre o problema não consegui resolver esse erro, poderiam me ajudar?

using Financas.Entidades;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Financas.DAO
{
    public class FinancasContexto : DbContext
    {
        public DbSet <Usuario> Usuarios { get; set; }
        public DbSet<Movimentacao> Movimentacoes { get; set; }

        //Chave estrangeira para o usuario

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Sobrescreve o metodo para o papeamento palo Entity
            //HasRequired diz que todo mapeamento tem obrigatoriamento um usuario
            modelBuilder.Entity<Movimentacao>().HasRequired(m => m.Usuario);
        }

    }
}
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>


  <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>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

  <!-- 
  A string de conexao foi pega no financas.mdf/propriedades/connectionString
  o caminho com '\' relacionando ao diretorio da pasta na maquina é 
  substituido por 'DataDirectory'


  Foi o nome de 'FinancasContext' a string de conexao o mesmo da classe de referencia ao Entity

  Pelo Package Console habilito pelo comando 'Enable-Migrations'
  as migrations para o Entity fazer migração dentro do projeto


  Se tudo der certo será criado dentro do projeto uma pasta chamado migrations

  Com o camando 'add-migration TabelasInicias' crio as tabelas do banco


  <configSections>

    <section name="conexao" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>


 -->

  <configuration>

     <add  name="FinancasContext"  providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0; 
                            AttachDbFilename=|DataDirectory|financas.mdf;
                            Integrated Security=True" 
     />    
  </configuration>
  <configSection>
    <!-- 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" />
  </configSection>


</configuration>
3 respostas

Oi Cleiton, tudo bem? Pode postar aqui a mensagem completa da exceção, por favor? Assim podermos investigar melhor o problema. Obrigado!

Marcelo, segue o código como solicitou.

======================================================================

PM> Enable-Migrations Checking if the context targets an existing database... System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration1' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section entityFramework. (C:\Users\cleit.DESKTOP-UQ67P4O\Desktop\Cursos\mvc_5\WebApp\Financas\Financas\tmpC2C4.tmp line 17) at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal) at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors) at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors() at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey) --- End of inner exception stack trace --- at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey) at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName) at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName) at System.Configuration.ConfigurationManager.get_ConnectionStrings() at System.Data.Entity.Internal.AppConfig..ctor() at System.Data.Entity.Internal.AppConfig..cctor() --- End of inner exception stack trace --- at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint) at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType) at System.Data.Entity.Migrations.DbMigrationsConfiguration1..cctor() --- End of inner exception stack trace --- at System.Data.Entity.Migrations.DbMigrationsConfiguration1..ctor() at Financas.Migrations.Configuration..ctor() in c:\Users\cleit.DESKTOP-UQ67P4O\Desktop\Cursos\mvc_5\WebApp\Financas\Financas\Migrations\Configuration.cs:line 10 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Data.Entity.Migrations.Utilities.MigrationsConfigurationFinder.FindMigrationsConfiguration(Type contextType, String configurationTypeName, Func2 noType, Func3 multipleTypes, Func3 noTypeWithName, Func3 multipleTypesWithName) at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration() at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run() at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace) at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration1' threw an exception. PM>

Obrigado pela resposta! Você pode abrir o arquivo "C:\Users\cleit.DESKTOP-UQ67P4O\Desktop\Cursos\mvc_5\WebApp\Financas\Financas\tmpC2C4.tmp" e verificar a linha 17?