Entity Framework 6: Error getting SQL Server record

Asked

Viewed 151 times

-1

I can enter records in the bank normally, however, when trying to get, it gives error in EF.

public class Program {
    public static void Main(string[] args) {
        new ClienteConsole().ConsoleListarCliente(1);
    }
}

public class ClienteConsole {
    public void ConsoleListarCliente(int matricula)
    {
        try
        {
            var dao = new ClienteDao();
            var cliente = dao.ObterCliente(matricula);
            ...
        }
        catch (Exception e)
        {
            System.Console.WriteLine(e.Message);
            System.Console.WriteLine(e.StackTrace);
        }
    }
}

public class ClienteDao
{
    private MyContext _db = new MyContext();

    public void Cadastrar(Cliente cliente)
    {
        _db.Set<Cliente>().Add(cliente); //Sem erro.
        _db.SaveChanges();
    }

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

An exception was triggered by the destination of a call.

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 MyProject.Infra.Data.Dao.ClienteDao.ObterCliente(Int32 matricula) na D:\Raphael\C#\MyProject\MyProject.Infra.Data\Dao\ClienteDao.cs:linha 28

em MyProject.Console.Console.ClienteConsole.ConsoleListarCliente(Int32 matricula) na D:\Raphael\C#\MyProject\MyProject.Console\Console\ClienteConsole.cs:linha 120

After removing the "Try-catch" structure, the following exception is released:

Invalidoperationexception: The class 'Client' has no parameterless constructor.

  • Have some information in the exceptions Inner?

  • The client id is actually an int?

  • @Linq as Inners exceptions would be Exception? because I only put this in the catch.

  • @Gabrielcoletta yes, the client id is an int

  • @Raphael What catch do you say?

  • of "Try catch".

  • 2

    I know that, my son. I want to know where this catch, because the question code has none of that.

  • Oh yes, in the Main method I called this method by passing the Try-catch.

  • I’ll edit the code.

  • @Raphael Beauty, then take this deal (the Try-catch) because he is hiding the details of the exception.

  • This is one of the major problems of the under-utilisation of the exception mechanism.

  • @Raphael Take this Try-catch, run again, post the error details

  • @LINQ added.

  • 1

    Make a constructor for Client protected, the framework needs a constructor without parameters.

  • Ah, now it worked out! Thanks @Gabrielcoletta and LINQ, I didn’t know that.

  • 2

    @Raphael Here’s a tip for life: never capture an exception if you’re not going to do anything with it.

  • @LINQ All right! Thank you.

Show 12 more comments

1 answer

3


Entity Framework requires a constructor with no parameters in models.

public class Cliente
{
    public Cliente() { }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.