Перейти к содержимому

Sequence contains no elements что за ошибка

  • автор:

Sequence contains more than one matching element в FirstOrDefault

Получаю ошибку Sequence contains more than one matching element в методе FirstOrDefault. Ошибка появляется в проекте с тестами. Версия EF фреймворков одинаковая. Разница только в версии .NET, основной проект .NET 5.0, проект с тестами .NET 6.0, я очень сомниваюсь что проблема в этом. Получаю ошибку в тесте:

Message: System.TypeInitializationException : The type initializer for ‘Microsoft.EntityFrameworkCore.Query.QueryableMethods’ threw an exception. —- System.InvalidOperationException : Sequence contains more than one matching element Stack Trace: QueryableMethods.get_Select() QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) MethodCallExpression.Accept(ExpressionVisitor visitor) ExpressionVisitor.Visit(Expression node) QueryTranslationPreprocessor.NormalizeQueryableMethod(Expression expression) QueryTranslationPreprocessor.Process(Expression query) QueryCompilationContext.CreateQueryExecutor[TResult](Expression query) Database.CompileQuery[TResult](Expression query, Boolean async) QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async) <>c__DisplayClass9_0 1.b__0() CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func 1 compiler) QueryCompiler.Execute[TResult](Expression query) EntityQueryProvider.Execute[TResult](Expression expression) Queryable.FirstOrDefault[TSource](IQueryable 1 source, Expression 1 predicate) MainAPIService.ctor(AppDBContext context, String serverCode, Boolean SSLIgnore) line 24 Service1C8.ctor(AppDBContext context) line 12 Service1C8Tests.CreateRepositoryAsync() line 53 Service1C8Tests.GetGasInfoAsyncNotNULLResult() line 38 <>c.b__128_0(Object state) —— Inner Stack Trace —— ThrowHelper.ThrowMoreThanOneMatchException() Enumerable.TryGetSingle[TSource](IEnumerable 1 source, Func 2 predicate, Boolean& found) Enumerable.Single[TSource](IEnumerable 1 source, Func 2 predicate) QueryableMethods.cctor()

Сам тест:

public class Service1C8Tests < private DbContextOptionsdbContextOptions; public Service1C8Tests() < var dbName = $"AuthorPostsDb_"; dbContextOptions = new DbContextOptionsBuilder() .UseInMemoryDatabase(dbName) .Options; > [Fact] public async void SaveTimeOnPointAsyncNotNULLResult() < //Arrange Service1C8 service = await CreateRepositoryAsync(); var test = DateTime.Now.ToString("yyyyMMddHHmmss"); //Act ResponseModel1C result = await service.SaveTimeOnPointAsync("123456", "10", "in"); //Assert Assert.NotNull(result); >[Fact] public async void GetGasInfoAsyncNotNULLResult() < //Arrange Service1C8 service = await CreateRepositoryAsync(); var test = DateTime.Now.ToString("yyyyMMddHHmmss"); //Act GasResponseModel1C result = await service.GetGasInfoAsync("123456", GasTypeInfo.History); //Assert Assert.NotNull(result); >private async Task CreateRepositoryAsync() < AppDBContext context = new AppDBContext(dbContextOptions); await PopulateDataAsync(context); return new Service1C8(context); >private async Task PopulateDataAsync(AppDBContext context) < context.RemoteServers.Add(new RemoteServer < Code = "Service1C8", Host = "some", Port = "80", SSL = false, Login = "testserv", Password = "1", Token = "dGVzdHasdas==", TokenLifeEnd = DateTime.Parse("2023-10-19 13:15:26.2500954"), AuthorizationHeader = "Basic" >); await context.SaveChangesAsync(); > > 

Место где она появляеться:

protected MainAPIService(AppDBContext context, string serverCode, bool SSLIgnore = false) < _context = context; _server = _context.RemoteServers .Include(rs =>rs.ServiceProxy) .FirstOrDefault(s => s.Code == serverCode); //Вот тут выстреливает ексепшен, который я привел выше. if(_server == null) < throw new Exception($"Remote server is NULL! Check DB table!"); > else < WebProxy proxy = null; if (_server.UseProxy) < proxy = new WebProxy() < Address = (new UriBuilder( _server.ServiceProxy.ProxySSL ? "https" : "http", _server.ServiceProxy.ProxyHost, _server.ServiceProxy.ProxyPort)).Uri, UseDefaultCredentials = _server.ServiceProxy.UseDefaultCredentials, BypassProxyOnLocal = _server.ServiceProxy.BypassProxyOnLocal, >; if(!_server.ServiceProxy.UseDefaultCredentials) < proxy.Credentials = new NetworkCredential( userName: _server.ServiceProxy.Login, password: _server.ServiceProxy.Password ); >> _httpHelper = new HTTPHelper( _server.Host, _server.Port, _server.SSL, SSLIgnore, proxy ); TokenAlive = DateTime.Now < _server.TokenLifeEnd; if(TokenAlive) < _httpHelper.SetAuthToken(_server.Token, _server.AuthorizationHeader); >> > 

UPD:
EF версия в обоих проектах:5.0.3 AppDbContext:

public class AppDBContext:DbContext < public DbSetRemoteServers < get; set; >public AppDBContext(DbContextOptions options) : base(options) < >protected override void OnModelCreating(ModelBuilder modelBuilder) < modelBuilder.Entity().HasData( new RemoteServer[] < new RemoteServer < Code="RemoteIntegrationServer", Host="", Port="", Login="", Password = "", Name="", SSL=false, Token="", AuthorizationHeader="Bearer", UseProxy = false>, new RemoteServer < Code="SignServer", Host="", Port="", Login="", Password = "", Name="", SSL=false, Token="", AuthorizationHeader="Bearer", UseProxy = false>, new RemoteServer < Code="FireBaseProxy", Host="", Port="", Login="", Password = "", Name="", SSL=false, Token="", AuthorizationHeader="Bearer", UseProxy = false>, new RemoteServer < Code="AlarmServer", Host="", Port="", Login="", Password = "", Name="", SSL=false, Token="", AuthorizationHeader="Bearer", UseProxy = false>, new RemoteServer < Code="PortalUZDServer", Host="", Port="", Login="", Password = "", Name="", SSL=true, Token="", AuthorizationHeader="Bearer", UseProxy = false>, new RemoteServer < Code="Service1C8", Host="", Port="", Login="", Password = "", Name="", SSL=false, Token="", AuthorizationHeader="Basic", UseProxy = false>, new RemoteServer < Code="VodafoneService", Host="", Port="", Login="", Password = "", Name="", SSL=true, Token="", AuthorizationHeader="Bearer", UseProxy = false>, > ); base.OnModelCreating(modelBuilder); > > 

Global Query Filters нет, Interceptors тоже нет.

Sequence contains no elements?

The query is fine when retrieving the row to put data in to the text boxes, but it returns an error «Sequence contains no elements» when used to retrieve the row in order to edit it and put it back in to the database. I can’t understand why it might find an appropriate row in one instance but not another. (Using ASP.NET MVC and LINQ)

72.6k 43 43 gold badges 129 129 silver badges 157 157 bronze badges
asked Aug 24, 2009 at 19:19
Andy Hunt Andy Hunt
you have to use SingleOrDefault , it will return null if no items returned
Dec 26, 2012 at 9:24

the error is saying it can not find any items in dc.BlogPosts which match the value of ID. Either ID has no value or the items in your list contain that item. Use SingleOrDefault or FirstOrDefault, these will return a null object if no item if found rather than error.

Mar 9, 2020 at 13:04

The question here is not to explain the meaning of «Sequence contains no elements», as many apparently think, but why it occurs. That question can’t be answered because it lacks details.

Sequence contains no elements, ERROR

Not sure how to interpret this
db.tblSWATScores.Single(e => e.SurveyID == tblswatwaprecipitation.SurveyID && e.VarName == «precipTotal»).Value = precipTotal;135297-waprecipitationcontroller.txt
it is an old Entity Framework application that I am trying to reconstruct and get running.

Server Error in ‘/’ Application.
Sequence contains no elements
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Sequence contains no elements

> Source Error:
>
>
> Line 69: //robm
> Line 70:
> Line 71: db.tblSWATScores.Single(e => e.SurveyID == tblswatwaprecipitation.SurveyID && e.VarName == «precipTotal»).Value = precipTotal;
> Line 72: if (precipTotal != null)
> Line 73: <
>
> Source File: D:\code\SwatCORS\merrittr-swat-0bfb4e658cdd\SWAT_legacy\SWAT-Source Code\SWAT\SWAT\Controllers\WAPrecipitationController.cs Line: 71
>
> Stack Trace:

Entity Framework 6.0

A Microsoft open-source object-database mapper for .NET.

why I got this error Sequence contains no elements?

I am using the following code in the view and tried a lot of solutions but still get this error
Sequence Contains no elements , this is the view code :

 @model AljawdahNewSite.Models.Orders_Tables @< ViewBag.Title = "Result Details"; //Layout = "~/Views/Shared/_LayoutPatients.cshtml"; var hema = new List() < 1 >; var bio = new List() < 2 >; var ser = new List() < 3 >; var hor = new List() < 4 >; var histo = new List() < 5 >; var culture = new List() < 8 >; var para = new List() < 6 >; var covid = new List() < 9 >; var labPara = Model.LabParaResult.FirstOrDefault(); var labCult = Model.LabCultureResults.FirstOrDefault(); var labMicro = Model.LabMicroResults.FirstOrDefault(); var labHisto = Model.LabHistoResult.FirstOrDefault(); var LabResults = Model.LabResults; var labhema = LabResults.FirstOrDefault(x => x.deptid == 1); var labBio = LabResults.FirstOrDefault(x => x.deptid == 2); var labSer = LabResults.FirstOrDefault(x => x.deptid == 3); var labHor = LabResults.FirstOrDefault(x => x.deptid == 4); var labcovid = LabResults.FirstOrDefault(x => x.deptid == 9); var LABCLINICVIEW = Model.labClinicsViewResult; var LABCASHVIEW = Model.labCashView; var labPara1 = Model.LabParasitologyView.FirstOrDefault(); var labCult1 = Model.LabCulturesView.FirstOrDefault(); var labMicro1 = Model.LabMicroView.FirstOrDefault(); var labHisto1 = Model.LabHistopathologyView.FirstOrDefault(); var labhema1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 1); var labBio1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 2); var labSer1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 3); var labHor1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 4); var labcovid1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 9); > 

this is part of controller code :

public ActionResult MasterDetails(int id) < var tables = new Orders_Tables < testsRanges = db.TestsRanges.ToList(), LabResults = db.LAB_RESULTS.Where(o =>o.ORDER_ID == id) .Include(p => p.LabTests) .Include(t => t.Patients).ToList(), LabParaResult = db.LAB_PARA_RESULTS.Where(o => o.ORDER_ID == id).Include(t => t.Patients).Include(t => t.LabTests).Include(c => c.Customers).ToList(), LabCultureResults = db.LAB_CULTURE_RESULT.Where(o => o.ORDER_ID == id).Include(t => t.Patients).Include(t => t.LabTests).Include(c => c.Customers).ToList(), LabMicroResults = db.LAB_MICRO_NEGATIVE_RESULT.Where(o => o.ORDER_ID == id).ToList(), labCashView = db.LAB_RESULT_CASH_VIEW.Where(o => o.order_number == id).ToList(), labClinicsViewResult = db.LAB_RESULTS_CLINIC_VIEW.Where(o => o.order_number == id).ToList(), LabParasitologyView = db.LAB_PARASITOLOGY_VIEW.Where(o => o.order_number == id).ToList(), >; return View(tables); > 

the error show when try to run the result for

var labPara1 = Model.LabParasitologyView.FirstOrDefault(); 

but the error appear in this line

var labcovid1 = LABCLINICVIEW.FirstOrDefault(x => x.DEPTID == 9); 

141450-sequence-contains-error.png

I need your help please :

How I will handle the controller code

If labClinicsViewResult is empty and returned no value skip and go to the next

ASP.NET MVC

A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *