I'm trying to add a limit GET query parameter in my API request (i.e. ?limit=10) and the value of this limit will then be used by the Take() LINQ method to get only the number of results I want. What I want to do is to include the LINQ Take() method as part of the LINQ-TO-T-SQL query and perform the limit as part of the SQL query. I tried the following codes below. I also captured the error stack trace.
Code 1: For this code, I'm trying to use the Take() on my top level resource in the query. Then afterwards (in the declaration of q), I'm performing sub-queries related to the top level resource.
baseQuery = baseQuery.Take(2);
var q = from doctor in baseQuery
let sp = (from ds in db.DoctorSpecialty
join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
where ds.DoctorID == doctor.DoctorID
select new
{
s.SpecialtyID,
s.Specialty1
}).ToList()
let clinics = (from c in db.Clinic
where c.DoctorID == doctor.DoctorID && c.Active == true
let schedule = (from sc in db.Schedule
where sc.ClinicID == c.ClinicID
&& sc.DoctorID == doctor.DoctorID
&& DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
select sc).ToList()
select new
{
c.ClinicID,
c.Street,
c.ClinicName,
c.ContactNumber,
c.City,
c.Province,
c.HomeNumber,
c.MobileNumber,
c.WorkNumber,
c.Email,
Schedules = schedule,
}).ToList()
select new
{
Doctor = doctor,
Specialties = sp,
Clinics = clinics
};
var rs = q.ToList();
Error stack trace for code 1:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (5ms) [Parameters=[#__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
SELECT [t].[DoctorID], [t].[Address], [t].[AvailableInvites], [t].[Birthdate], [t].[City], [t].[CityID], [t].[ContactNumber], [t].[Country], [t].[DateRegistered], [t].[Description], [t].[DoctorUrl], [t].[Email], [t].[EmailActivated], [t].[EmailUID], [t].[EmailVerifiedFirstTime], [t].[Facebook], [t].[FirstName], [t].[Gender], [t].[GooglePlus], [t].[HomeNumber], [t].[Image], [t].[LastName], [t].[LinkedIn], [t].[MainSpecialty], [t].[ManuallyVerified], [t].[MedicalSchool], [t].[MedicalSchoolYear], [t].[MiddleName], [t].[MobileNumber], [t].[Nationality], [t].[OriginalIssueDate], [t].[PRCNumber], [t].[PageOkay], [t].[PatientNumber], [t].[PhicNumber], [t].[PractisingSince], [t].[Province], [t].[PtrNumber], [t].[Residency], [t].[ResidencyYear], [t].[S2Number], [t].[ShowPublicProfile], [t].[Status], [t].[Street], [t].[Suffix], [t].[Title], [t].[Twitter], [t].[UserID], [t].[Website], [t].[WorkNumber], [t].[Zipcode], [t0].[SpecialtyID], [t0].[Specialty], [t0].[Id], [t2].[ClinicID], [t2].[Street], [t2].[ClinicName], [t2].[ContactNumber], [t2].[City], [t2].[Province], [t2].[HomeNumber], [t2].[MobileNumber], [t2].[WorkNumber], [t2].[Email], [t2].[ScheduleID], [t2].[Active], [t2].[ClinicID0], [t2].[DateModified], [t2].[DayOfWeek], [t2].[DoctorID], [t2].[Notes], [t2].[StartFrom], [t2].[TimeEnd], [t2].[TimeStart], [t2].[Until]
FROM (
SELECT TOP(#__p_0) [d].[DoctorID], [d].[Address], [d].[AvailableInvites], [d].[Birthdate], [d].[City], [d].[CityID], [d].[ContactNumber], [d].[Country], [d].[DateRegistered], [d].[Description], [d].[DoctorUrl], [d].[Email], [d].[EmailActivated], [d].[EmailUID], [d].[EmailVerifiedFirstTime], [d].[Facebook], [d].[FirstName], [d].[Gender], [d].[GooglePlus], [d].[HomeNumber], [d].[Image], [d].[LastName], [d].[LinkedIn], [d].[MainSpecialty], [d].[ManuallyVerified], [d].[MedicalSchool], [d].[MedicalSchoolYear], [d].[MiddleName], [d].[MobileNumber], [d].[Nationality], [d].[OriginalIssueDate], [d].[PRCNumber], [d].[PageOkay], [d].[PatientNumber], [d].[PhicNumber], [d].[PractisingSince], [d].[Province], [d].[PtrNumber], [d].[Residency], [d].[ResidencyYear], [d].[S2Number], [d].[ShowPublicProfile], [d].[Status], [d].[Street], [d].[Suffix], [d].[Title], [d].[Twitter], [d].[UserID], [d].[Website], [d].[WorkNumber], [d].[Zipcode]
FROM [Doctor] AS [d]
WHERE [d].[Status] = 'good'
) AS [t]
LEFT JOIN (
SELECT [s].[SpecialtyID], [s].[Specialty], [d0].[Id], [d0].[DoctorID]
FROM [DoctorSpecialty] AS [d0]
INNER JOIN [Specialty] AS [s] ON [d0].[SpecialtyID] = [s].[SpecialtyID]
) AS [t0] ON [t].[DoctorID] = [t0].[DoctorID]
LEFT JOIN (
SELECT [c].[ClinicID], [c].[Street], [c].[ClinicName], [c].[ContactNumber], [c].[City], [c].[Province], [c].[HomeNumber], [c].[MobileNumber], [c].[WorkNumber], [c].[Email], [t1].[ScheduleID], [t1].[Active], [t1].[ClinicID] AS [ClinicID0], [t1].[DateModified], [t1].[DayOfWeek], [t1].[DoctorID], [t1].[Notes], [t1].[StartFrom], [t1].[TimeEnd], [t1].[TimeStart], [t1].[Until], [c].[DoctorID] AS [DoctorID0]
FROM [Clinic] AS [c]
LEFT JOIN (
SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
FROM [Schedule] AS [s0]
WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
WHERE [c].[Active] = CAST(1 AS bit)
) AS [t2] ON [t].[DoctorID] = [t2].[DoctorID0]
ORDER BY [t].[DoctorID], [t0].[Id], [t0].[SpecialtyID], [t2].[ClinicID], [t2].[ScheduleID]
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'SeriousMDCommonsCore.Models.Database.SeriousmdEntitiesContext'.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM03JVLBFS8O", Request id "0HM03JVLBFS8O:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
Code 2: Here, instead of performing the Take() in the baseQuery, I'm performing the Take() in the final query expression q. I also added a doctor.DoctorID as some sort of id that I think is required to be fed to the Take() LINQ method
var q = from doctor in baseQuery
let sp = (from ds in db.DoctorSpecialty
join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
where ds.DoctorID == doctor.DoctorID
select new
{
s.SpecialtyID,
s.Specialty1
}).ToList()
let clinics = (from c in db.Clinic
where c.DoctorID == doctor.DoctorID && c.Active == true
let schedule = (from sc in db.Schedule
where sc.ClinicID == c.ClinicID
&& sc.DoctorID == doctor.DoctorID
&& DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
select sc).ToList()
select new
{
c.ClinicID,
c.Street,
c.ClinicName,
c.ContactNumber,
c.City,
c.Province,
c.HomeNumber,
c.MobileNumber,
c.WorkNumber,
c.Email,
Schedules = schedule,
}).ToList()
select new
{
doctor.DoctorID,
Doctor = doctor,
Specialties = sp,
Clinics = clinics
};
q = q.Take(2);
var rs = q.ToList();
Error stack trace for code 2: Here, the error changed from that of code 2 and it seems that the added index is being used by the Take() LINQ method but still throws an error.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM03K296O68T", Request id "0HM03K296O68T:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Processing of the LINQ expression '(ProjectionBindingExpression: 0)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Back to my question, how can I integrate the Take() LINQ method as part of my LINQ-TO-T-SQL query so that all of my queries will go through EF Core and all query operations will be performed in database?
In the first query try changing doctor.DoctorID in:
let schedule = (from sc in db.Schedule
where sc.ClinicID == c.ClinicID
&& sc.DoctorID == doctor.DoctorID
&& DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
select sc)
to c.DoctorID:
let schedule = (from sc in db.Schedule
where sc.ClinicID == c.ClinicID
&& sc.DoctorID == c.DoctorID
&& DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
select sc)
UPD
If you go through the SQL you will see the code generated for schedules:
LEFT JOIN (
SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
FROM [Schedule] AS [s0]
WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
Check out the where clause it has WHERE ([s0].[DoctorID] = [d].[DoctorID]) condition which references [d].[DoctorID] which is not accessible cause it is accessible only in the root subselect which performs Take. It seems that there is a convoluted bug in EF Core.
Code 3: This version of my code successfully returns the number of results I wanted via the Take() LINQ method. However, the Take() is being performed on data / collection that is already loaded in the client side or in memory. So this Take() performs a LINQ-TO-Collections query instead of LINQ-TO-T-SQL and doesn't go through EF Core.
var q = from doctor in baseQuery
let sp = (from ds in db.DoctorSpecialty
join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
where ds.DoctorID == doctor.DoctorID
select new
{
s.SpecialtyID,
s.Specialty1
}).ToList()
let clinics = (from c in db.Clinic
where c.DoctorID == doctor.DoctorID && c.Active == true
let schedule = (from sc in db.Schedule
where sc.ClinicID == c.ClinicID
&& sc.DoctorID == doctor.DoctorID
&& DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
select sc).ToList()
select new
{
c.ClinicID,
c.Street,
c.ClinicName,
c.ContactNumber,
c.City,
c.Province,
c.HomeNumber,
c.MobileNumber,
c.WorkNumber,
c.Email,
Schedules = schedule,
}).ToList()
select new
{
Doctor = doctor,
Specialties = sp,
Clinics = clinics
};
var rs = q.ToList();
rs = rs.AsEnumerable().Take(2).ToList();
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.ComponentModel.Win32Exception: The wait operation timed out
Source Error:
Line 1399: dataTable.Clear();
Line 1400: }
Line 1401: int returnValue = this.Adapter.Fill(dataTable);
Line 1402: return returnValue;
Line 1403: }
Source File: c:\Users\PC\AppData\Local\Temp\Temporary ASP.NET Files\vs\8562cbc5\e7d18687\App_Code.ilsptr20.77.cs Line: 1401
Stack Trace:
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +212
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +81
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +631
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4234
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) +438
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2620
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +1635
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +244
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +37
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +138
System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) +157
System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) +106
DSFinalPercentageTableAdapters.spTotalPercentageTableAdapter.FillByClass(spTotalPercentageDataTable dataTable, Nullable`1 classid, Nullable`1 eng) in c:\Users\PC\AppData\Local\Temp\Temporary ASP.NET Files\vs\8562cbc5\e7d18687\App_Code.ilsptr20.77.cs:1401
xpTotalPercentage.xpTotalPercentage_BeforePrint(Object sender, PrintEventArgs e) in f:\Slim\App_Code\xpTotalPercentage.cs:452
DevExpress.XtraReports.UI.XRControl.OnBeforePrint(PrintEventArgs e) +262
DevExpress.XtraReports.UI.XtraReport.OnBeforePrint(PrintEventArgs e) +304
DevExpress.XtraReports.UI.XtraReport.TryCreateDocumentCore(Single progressRange, Boolean buildPagesInBackground) +44
DevExpress.XtraReports.UI.XtraReport.TryCreateDocument(Single progressRange, Boolean buildPagesInBackground) +78
[Exception: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
DevExpress.XtraPrinting.PrintingSystemBase.OnCreateDocumentException(ExceptionEventArgs args) +175
DevExpress.XtraReports.UI.XtraReport.TryCreateDocument(Single progressRange, Boolean buildPagesInBackground) +298
DevExpress.XtraReports.UI.XtraReport.CreateDocument(Boolean buildForInstantPreview) +12
DevExpress.XtraReports.UI.XtraReport.CreateDocument() +15
Forms_StudentFinalPercentageReport.getReport() in f:\Slim\Forms\StudentFinalPercentageReport.aspx.cs:122
Forms_StudentFinalPercentageReport.Page_Load(Object sender, EventArgs e) in f:\Slim\Forms\StudentFinalPercentageReport.aspx.cs:23
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +85
System.Web.UI.Control.OnLoad(EventArgs e) +79
System.Web.UI.Adapters.ControlAdapter.OnLoad(EventArgs e) +12
System.Web.UI.Control.LoadRecursive() +98
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2853
I've built a MVC web application and need to generate a unique sequential serial number by application type and year when users submit a form.
The serial number will be stored in the database table MyAppCodeSEQ and the column "AppCode" is a PK of MyAppCodeSEQ.
This is my code below:
public MyAppCodeSEQ GenNewAppCode(string appType)
{
MyAppCodeSEQ model = null;
try
{
var today = DateTime.Now;
int maxSeq = _db.MyAppCodeSEQ.Where(x => x.AppType == appType && x.Year == today.Year).Select(x => x.SEQ).DefaultIfEmpty(0).Max();
maxSeq = maxSeq + 1;
var appCode = "XX" + appType + today.Year % 1000 + string.Format("{0:000000}", maxSeq);
model = new MyAppCodeSEQ()
{
AppCode = appCode,
AppType = appType,
Year = today.Year,
SEQ = maxSeq,
};
_db.MyAppCodeSEQ.Add(model);
_db.SaveChanges();
}
catch(Exception e)
{
Thread.Sleep(100);
GenNewAppCode(appType);
}
return model;
}
The function will be recall while a duplicated key is inserted. however, the below error was occurred again and again.
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details.
---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_AppCodeSEQ'.
Cannot insert duplicate key in object 'dbo.MyAppCodeSEQ'. The duplicate key value is (XXYY18002193).
The statement has been terminated.
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
System.Data.SqlClient.SqlDataReader.get_MetaData()
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
System.Data.Entity.Internal.InternalContext.SaveChanges()
Is there any better solution to generate a serial number?
a) NEVER have a primary key that is editable, let the database generate the primary key
b) The fields you are talking about is a "candidate" key and the purpose is usually for "sorting" into a default sequence or for guaranteeing uniqueness
c) A sequential key is pretty much a meaningless piece of data
That said, here's one possibility:
Alter your class (MyAppCodeSEQ) to include an Added field as DateTime. Unique Index on AppCode, AppType, Year to prevent duplicates. Index on AppCode, AppType, Year, Added to preserve sequence.