Error in LINQ( Expression Lambda query)

Asked

Viewed 832 times

1

I have an appointment, which was working perfectly in my controller.

I made a change (I don’t know which one) and it stopped working. I don’t know what I did wrong, to stop working.

Error:

The sequence contains more than one matching element

Controlller:

public ActionResult Dependente(string name) {
    //Instancia obj da DLL
    Criptografia cr = new Criptografia();

    //Recebe oa string Criptografada
    string nome = Request.QueryString["param"];

    //Descriptografa a string
    string nomeDescrypt = cr.Decrypt(nome);

    //Separa a string por meio do "|"
    string[] stringSeparators = new string[] {
        "|"
    };
    var result = nomeDescrypt.Split(stringSeparators, StringSplitOptions.None);

    //Concerte para o tipo de dado correto
    var matricula = Convert.ToInt32(result[0]);
    var contrato = Convert.ToInt32(result[1]);

    //Salvar a session no Helper
    System.Web.HttpContext.Current.Session["Contrato"] = contrato; // valor do contrato = 11
    System.Web.HttpContext.Current.Session["Matricula"] = matricula; // valor da matricula = 9951

    var userMatricula = SessionHelper.Matricula; //valor da matricula = 9951

    var usuarios = usuarioRepository.Lista.Where(r = > r.CdMatricula == matricula && r.SqContrato == contrato).SingleOrDefault(); // valor da matricula: 9951, contrato: 11

    return View(usuarios);

}

Performing this same query in the database, returns me only 1 result.

Error generated:

[InvalidOperationException: A sequência contém mais de um elemento de correspondência]
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source, Func`2 predicate) +2533722
System.Data.Entity.Migrations.Infrastructure.<>c__DisplayClass250.    <FindAlteredColumns>b__247(<>f__AnonymousType2b`2 <>h__TransparentIdentifier242) +230
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +171
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source,     ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator     migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) +640
System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument   sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) +870
System.Data.Entity.Internal.InternalContext.ModelMatches(VersionedModel model) +151 System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +160
System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +102
System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +57
System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +206
System.Data.Entity.Internal.<>c__DisplayClassf`1.<CreateInitializationAction>b__e() +165
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +110
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +660
System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +31
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +143
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +292
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +123
System.Data.Entity.Internal.InternalContext.Initialize() +42
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +137
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +38
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +99
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
PortalRH.WebUI.Controllers.UsuarioController.Index(Usuario usuario) in c:\Users\renilson.meneguci\Documents\Visual Studio 2013\Projects\UEM_ES\Pronim LC Web\AS1311D01_01\Main\Fontes\GovBr_PRONIM_LCnet\PortalRH.WebUI\Controllers\UsuarioController.cs:126
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9715856
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
  • If you change the SingleOrDefault() for ToList(), how many elements come back?

  • The strange is this, returns me the same error and in the same place( in the query). And I can’t put a Breakpoint on my return, to see what’s returning.

  • @Renilsonandrade I suppose @Gypsy meant to take the SingleOrDefault. The exception is expected as more than one results are to be returned. It has probably changed from FirstOrDefault which returns the first widget of the collection, to SingleOrDefault that returns a single widget from a collection that can only have one widget.

  • @Omni, I tested these 3 options, and both returned me the same error. It was not to change the error at least?

  • @Renilsonandrade yes, and if it does not change it means that it is not running the correct code. If you are using Iisexpress to do the hosting, Exit, recompile, and run again. Place a breakpoint inside the controller. If breakpoint does not work (empty with a triangle) means that the source code is different from the code to be executed (in a simplified way)

  • @Omni, I use it. I’ve done it, restarted the machine and everything. But it’s the same thing.

  • @Renilsonandrade download the dotPeek and scan the running DLL and confirm the code change. Another suggestion is to delete the project’s /bin folder and compile again (and parse the code with dotPeek and see if it runs as expected)

Show 2 more comments

1 answer

0


Thank you all. I could not find the error, so I went back a previous Backup and I refilled the methods, after the same worked normally. I compared the two codes, and they are identical. But thank you to everyone who helped me.

Browser other questions tagged

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