EF Alter Table with FK error message - c#

I run in the following error message when I try to run the Seed method.
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: The INSERT statement conflicted
with the FOREIGN KEY constraint "FK_dbo.Movies_dbo.Genres_GenreId".
The conflict occurred in database
"C:\USERS\PATH\SOURCE\REPOS\MVCMOVIE\MVCMOVIE\APP_DATA\MOVIES.MDF",
table "dbo.Genres", column 'Id'. The statement has been terminated.
This is my Configuration.cs file
namespace MvcMovie.Migrations
{
using MvcMovie.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<MvcMovie.Models.MovieDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "MvcMovie.Models.MovieDBContext";
}
protected override void Seed(MvcMovie.Models.MovieDBContext context)
{
context.Genres.AddOrUpdate(i => i.Title,
new Genre
{
Title = "Comedy"
},
new Genre
{
Title = "Romantic"
});
context.Ratings.AddOrUpdate(i => i.Title,
new Rating
{
Title = "General"
},
new MvcMovie.Models.Rating
{
Title = "Parentel guidence"
});
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
GenreId = 1,
RatingId = 1,
Price = 7.99M
},
new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
GenreId = 1,
RatingId = 1,
Price = 8.99M
},
}
);
}
}
}
Rating and Genres are set to be FK in the Movie table. Has anyone had this type of error before?
The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at
System.Data.SqlClient.SqlDataReader.get_MetaData() at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString, Boolean
isInternal, Boolean forDescribeParameterEncryption) at
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) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand
t, DbCommandInterceptionContext1 c) at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed) at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext) at
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior) at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary2
identifierValues, List1 generatedValues) at
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
--- End of inner exception stack trace --- at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator
ut) at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T
noChangesResult, Func2 updateFunction) at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at
System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
options, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction) at
System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
options, Boolean executeInExistingTransaction) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
options) at
System.Data.Entity.Internal.InternalContext.SaveChanges() --- End
of inner exception stack trace --- at
System.Data.Entity.Internal.InternalContext.SaveChanges() at
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at
System.Data.Entity.DbContext.SaveChanges() at
System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String
targetMigration) at
System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.b__d()
at
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.DbMigrator.Update(String
targetMigration) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
targetMigration) at
System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()

Related

Azure SQL Database - Transient Fault Handling doesn't work

I tried to use SQL Azure Transient fault handling, but it doesn't seem to work. My Web Service still throws a transient error. Here is my code:
public int ExecuteSqlCmd(string sql, object[] parameters)
{
return (new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(10, TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(0.5))).ExecuteAction<int>(() =>
{
return this.Database.ExecuteSqlCommand(sql, sqlParams);
});
}
Every now and then, it still throws this error:
System.Data.Entity.Core.EntityException: An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy. ---> System.Data.SqlClient.SqlException: Transaction (Process ID 84) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at 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)
at 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)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommandInternal(String commandText, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass174_0.<ExecuteStoreCommand>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
--- End of inner exception stack trace ---
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
...
...
...
Any idea why? I have spent days trying to figure out the solution to this problem.
Thanks

Use of Take() LINQ Method in Entity Framework Core v3.1.4

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();

The wait operation timed out in devexpress report

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

How to gen a sequential unique number by difference app type

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.

Entity Framework 7 Beta5 - DbUpdateException resolution

I am having issues using the Entity Framework for simple CRUD operations. I do believe everything is configured correctly, but when I call SaveChanges after adding an entity to a DbSet, a DbUpdateException is thrown. I'm not quite sure which code to provide, so I'm going to include the exception detail and the logic involved.
Exception detail:
Microsoft.Data.Entity.Update.DbUpdateException occurred
HResult=-2146233088
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework.Relational
StackTrace:
at Microsoft.Data.Entity.Relational.Update.ReaderModificationCommandBatch.Execute(RelationalTransaction transaction, IRelationalTypeMapper typeMapper, DbContext context, ILogger logger)
at Microsoft.Data.Entity.Relational.Update.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.Data.Entity.Relational.RelationalDataStore.SaveChanges(IReadOnlyList`1 entries)
at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.Data.Entity.DbContext.SaveChanges()
at Uniti.Data.Repository`1.Add(T entity) in D:\Alex\Projects\Uniti\src\Uniti.Data\Repository.cs:line 38
InnerException:
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=2
Message=Invalid object name 'UnitiPost'.
Number=208
Procedure=""
Server=(localdb)\MSSQLLocalDB
Source=.Net SqlClient Data Provider
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.Data.Entity.Relational.Update.ReaderModificationCommandBatch.Execute(RelationalTransaction transaction, IRelationalTypeMapper typeMapper, DbContext context, ILogger logger)
InnerException:
Repository Add method
public bool Add(T entity)
{
_context.Add(entity);
_context.Entry(entity).State = EntityState.Added;
return _context.SaveChanges() > 0;
}
Controller action to add UnitiPost
[HttpPost]
[Route("Add")]
[Authorize("Bearer")]
public async Task<IActionResult> Add([FromBody] UnitiPostAddDto postAddModel)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(User.GetUserId());
var post = new UnitiPost
{
Creator = user,
CreateDateTime = DateTime.UtcNow,
UpdateDateTime = DateTime.UtcNow,
Content = postAddModel.Content
};
var add = Repository.Add(post);
if (!add)
{
return Json(false);
}
return Json(true);
}
return Json(new FailureResult(null, ModelState));
}
If you need more information to solve the issue, I will be able to give you individual access to my GitHub repo, but it is a private repo, so I cannot open it to everyone.

Categories