1

Estou tendo problemas com o Entity Framework 6 com Code First. As operações de "Select" dão erro e o EF6 não especifica a exceção, como mostrado abaixo:

Mensagem de Erro:

Uma exceção foi acionada pelo destino de uma chamada.

Pilha de Exceção:

em System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   em System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   em System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   em System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap(Translator translator, Type elementType, ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer)
   em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
   em System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
   em System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   em System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   em System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   em System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   em System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   em System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   em System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
   em System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   em System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   em System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
   em System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName)
   em System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues)
   em System.Data.Entity.DbSet`1.Find(Object[] keyValues)
   em ProjetoTeste.Infra.Data.Repositories.ClienteRepository.ObterCliente(Int32 id) na D:\Informática\Raphael\Projetos VS2015\ProjetoTeste\ProjetoTeste.Infra.Data\Repositories\ClienteRepository.cs:linha 43
   em ProjetoTeste.Domain.Services.ClienteService.ObterCliente(Int32 id) na D:\Informática\Raphael\Projetos VS2015\ProjetoTeste\ProjetoTeste.Domain\Services\ClienteService.cs:linha 29
   em ProjetoTeste.Application.Services.ClienteAppService.ObterCliente(Int32 id) na D:\Informática\Raphael\Projetos VS2015\ProjetoTeste\ProjetoTeste.Application\Services\ClienteAppService.cs:linha 30
   em ProjetoTeste.Web.Controllers.ClienteController.Details(Int32 id) na D:\Informática\Raphael\Projetos VS2015\ProjetoTeste\ProjetoTeste.Web\Controllers\ClienteController.cs:linha 93

A operação de inserção ocorre normalmente:

public void Adicionar(Cliente cliente)
{
    _db.Set<Cliente>().Add(cliente);
    _db.SaveChanges();
}

Mas as operações abaixo são as que lançam a exceção:

public ICollection<Cliente> ObterTodos()
{
    return _db.Set<Cliente>().ToList();            
}

public Cliente ObterCliente(int id)
{
    return _db.Set<Cliente>().Find(id);
}

Não testei a operação de "Update", pois, para isso, é necessário obter a entidade previamente para ela ficar no contexto do EF para assim poder atualizá-la.

  • O que, normalmente, pode ser isso?
5
  • O seu _db é o que? não tem como fazer return _db.Cliente.ToList(); 2/12/2016 às 19:55
  • O "_db" é o context.
    – Raphael
    2/12/2016 às 21:33
  • Em algum desses métodos você usa try-catch? Repositories.ClienteRepository.ObterCliente, Domain.Services.ClienteService.ObterCliente, Application.Services.ClienteAppService.ObterCliente ou Controllers.ClienteController.Details?
    – Jéf Bueno
    3/12/2016 às 16:19
  • Eu uso o padrão repositório, e deixo os "try-catchs" no controller.
    – Raphael
    5/12/2016 às 13:54

1 Resposta 1

-2

Cara seguinte tem nessa

public ICollection<Cliente> ObterTodos()
{
    return _db.Set<Cliente>().ToList();            
}

vc só esta entrando na classe sem fazer nenhuma consulta tenta assim

public ICollection<Cliente> ObterTodos()
{
    return _db.Set<Cliente>().OrderBy(p=> p.Id).ToList();            
}

essa expreção OrderBy(p=> p.Id) vai organizar em ordem crescente os resultados da sua classe Cliente que esta sendo representada por "p=" buscando pelo Id "p.Id"

é nessa outra função:

public Cliente ObterCliente(int id)
{
    return _db.Set<Cliente>().Find(id);
}

ficaria assim:

public Cliente ObterCliente(int id)
{
    return _db.Set<Cliente>().Find(p=> p.Id == Id);
}

Uma dica, procure por expressões Linq e expressões Lambda no C#. Espero ter ajudado!

1
  • Valeu Samuel, mas também deu o mesmo erro. Não tenho a mínima ideia do que pode ser, pois tenho um outro projeto que têm as mesmas configs e não têm nenhum problema. Vou ter que refazer todo o projeto, talvez dê certo.
    – Raphael
    5/12/2016 às 13:52

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .