FindByNameAsync throws a Drop Drop Database error in Entity Framework - c#

I have a problem that is confusing me, so I thought I should ask the community. I have implemented the EF user authentication functionality which works well from time to time, however from time to time, this line of code throws a Drop Database error.
var user = await UserManager.FindByNameAsync(userName);
I am not sure what could be causing the error and where I must check when this happens. Also why would it try to drop the database when all I am doing is selecting a record from the database?
UPDATE
After reading the comment, I thought I should try add more meat to my question.
I am trying to authenticate the user using the following piece of code.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
try
{
var securityService = GetFromContext<ISecurityService>(context);
var logger = GetFromContext<ILogger>(context);
var user = await securityService.AuthenticateAsync(context.UserName, context.Password);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(oAuthIdentity);
}
catch (Exception ex)
{
// Removed for brevity
}
}
The method AuthenticateUser looks like the following:
public async Task<SecureUser> AuthenticateAsync(string userName, string password, bool sendOtp = true)
{
var user = await GetUserByNameAsync(userName);
return user;
}
This calls the originally asked method on the following code:
public async Task<SecureUser> GetUserByNameAsync(string userName)
{
var user = await UserManager.FindByNameAsync(userName);
return user;
}
The method throws the following exception when called.
Exception Screenshot
Error message as a string
Cannot drop database XXXX because it is currently in use.
Unfortunately for security reasons I cannot share the database name.
The full stack trace is below
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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
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.SqlServer.SqlProviderServices.<>c__DisplayClass57_0.<DropDatabase>b__0(DbConnection conn)
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass60_0.<UsingConnection>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass2_0.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
at System.Data.Entity.SqlServer.SqlProviderServices.DropDatabase(SqlConnection sqlConnection, Nullable`1 commandTimeout, String databaseName)
at System.Data.Entity.SqlServer.SqlProviderServices.DbDeleteDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
at System.Data.Entity.Database.Delete()
at System.Data.Entity.DropCreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate)
at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<GetUserAggregateAsync>d__67.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Rica.Security.SecurityService`1.<GetUserByNameAsync>d__22.MoveNext() in C:\Repos\RICA\Rica.Security\SecurityService.cs:line 301
I hope the meat I added explains my problem slightly better.

This problem is caused by the fact that I have added a migration onto the application before running the Update-Database command.
So the model is dirty, and because of it being dirty, there is a command that EF has that is called DropDatabseIfModelChanges which tries to drop the database, however because the application is running and a connection has been established, I receieve that error.
I solved it but running my Update-Database command and the error was solved.

Related

EFMigrationsHistory table is empty

Im creating database in debug. When database not exist, i create new one:
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetService<LolDbContext>();
context?.Database.EnsureCreated();
if (context.Database.CanConnect())
{
context.Database.Migrate();
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger>();
logger.Error($"Exception while migrating db: {ex}");
}
}
host.Run();
}
After app starts i get this exception:
[11:47:10 [Error] Exception while migrating db: Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Table' in the database.
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at eSportsLab.LeagueOfLegends.Api.Frontend.Program.Main(String[] args) in D:\repos\lol-sumeron-app\LeagueOfLegends\Presentation\eSportsLab.LeagueOfLegends.Api.Frontend\Program.cs:line 32
ClientConnectionId:00b6a255-f82d-49b2-adf6-23b83d0aeb1b
Error Number:2714,State:6,Class:16
When i go to SSMS i can see created database (with tables, data as expected), but table [__EFMigrationsHistory] is empty. In another database everything works fine:
My question is, why EF dont tracking migrations when i initialize DB like that?
Shortly, you should not use EnsureCreated if you are using migrations.
Apply migrations at runtime section of the official EF Core documentation contains the following Warning:
Don't call EnsureCreated() before Migrate(). EnsureCreated() bypasses Migrations to create the schema, which causes Migrate() to fail.

SQL Server localDB could not create file

i am trying to recreate this sample
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/
I did everything according to the text, the program compiles fine, but then it fails creating the database
It seems like the db file
'C:\Users\WolfgangConsoleApp4.BlogContext.mdf' is missing a \ after Wolfgang.
But I do not know where to enter the path correctly.
On the laptop in my company I could rebuild and run the sample code without errors.
this is the complete exception text:
System.Data.SqlClient.SqlException
HResult=0x80131904
Nachricht = CREATE FILE encountered operating system error 5(Zugriff verweigert) while attempting to open or create the physical file 'C:\Users\WolfgangConsoleApp4.BlogContext.mdf'.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Quelle = .Net SqlClient Data Provider
Stapelüberwachung:
bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
bei System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c.<NonQuery>b__4_0(DbCommand t, DbCommandInterceptionContext`1 c)
bei System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
bei System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
bei System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass52_0.<CreateDatabaseFromScript>b__0(DbConnection conn)
bei System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass60_0.<UsingConnection>b__0()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass2_0.<Execute>b__0()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
bei System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
bei System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
bei System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
bei System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
bei System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
bei System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
bei System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
bei System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
bei System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
bei System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
bei System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
bei System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
bei System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
bei System.Data.Entity.Internal.InternalContext.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0()
bei System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
bei System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
bei System.Data.Entity.Internal.LazyInternalContext.<>c.<InitializeDatabase>b__58_0(InternalContext c)
bei System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
bei System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
bei System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
bei System.Data.Entity.Internal.InternalContext.Initialize()
bei System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
bei System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
bei System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
bei System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
bei System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
bei System.Data.Entity.DbSet`1.Add(TEntity entity)
bei ConsoleApp4.Program.Main(String[] args) in C:\Users\Wolfgang\source\repos\ConsoleApp4\ConsoleApp4\Program.cs: Zeile29
Maybe my VS Community Edition does not allow this?
Or maybe I have too many versions of sql server and localdb and so installed?
Greetings
Wolfgang
As #ErikEJ posted in a comment, I have to update my localdb install.
For this i used Cumulative Update 6 for SQL Server 2017.
After a restart of the pc it worked.
But code first migrations were not what i initially was searching for...
I think, I will have to post a new question...

Implementation of Hard Delete for Entity which is being referred in other entity

I'm trying to implement hard delete for FullyAuditedEntity Entity Test. The primary key of Test is Id, which is being referred to a TestTest2 entity as a foreign key. When I'm trying to delete a record from Test entity, it gives the below error.
I have followed this question for implementation.
TestAppService
public async Task DeleteTest(EntityDto<string> input)
{
using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete))
{
await _TestRepository.DeleteTest(input);
CurrentUnitOfWork.SaveChanges();
}
}
TestRepository
public async Task DeleteArticle(EntityDto input)
{
await DeleteAsync(x => x.Id == input.Id);
}
TestTest2
[Table("TestTest2")]
public class TestTest2 : FullAuditedEntity
{
[ForeignKey("TestId")]
public virtual Test Test { get; set; }
public virtual string TestId { get; set; }
[ForeignKey("Test2Id")]
public virtual Test2Details Test2s { get; set; }
public virtual int Test2Id { get; set; }
}
MyProjectDbContextModelSnapshot
modelBuilder.Entity("MyCompany.MyProject.Business.Model.Tests.TestTest2Association", b =>
{
b.HasOne("MyCompany.MyProject.Business.Model.Tests.Test", "Test")
.WithMany()
.HasForeignKey("TestId");
b.HasOne("MyCompany.MyProject.Business.Model.Test2s.Test2Details", "Test2s")
.WithMany()
.HasForeignKey("Test2Id")
.OnDelete(DeleteBehavior.Cascade);
});
ERROR 2018-02-28 18:10:09,840 [26 ]
Mvc.ExceptionHandling.AbpExceptionFilter - An error occurred while
updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred
while updating the entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: The DELETE statement conflicted
with the REFERENCE constraint "FK_TestTest2_Test_TestId". The conflict
occurred in database "MyProjectDb", table "dbo.TestTest2", column
'TestId'. The statement has been terminated. at
System.Data.SqlClient.SqlConMyCompanytion.OnError(SqlException
exception, Boolean breakConMyCompanytion, Action1 wrapCloseInAction)
at
System.Data.SqlClient.SqlInternalConMyCompanytion.OnError(SqlException
exception, Boolean breakConMyCompanytion, Action1 wrapCloseInAction)
at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConMyCompanytionLock, 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) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream,
TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean
asyncWrite, String method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior) at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) at System.Data.Common.DbCommand.ExecuteReader() at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConMyCompanytion
conMyCompanytion, DbCommandMethod executeMethod, IReadOnlyDictionary2
parameterValues) at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConMyCompanytion
conMyCompanytion, IReadOnlyDictionary2 parameterValues) at
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConMyCompanytion
conMyCompanytion) --- End of inner exception stack trace --- at
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConMyCompanytion
conMyCompanytion) at
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2
parameters) at
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState
state, Func3 operation, Func3 verifySucceeded) at
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy
strategy, TState state, Func2 operation) at
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1
commandBatches, IRelationalConMyCompanytion conMyCompanytion) at
Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1
entries) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1
entriesToSave) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean
acceptAllChangesOnSuccess) at
Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean
acceptAllChangesOnSuccess) at
Abp.EntityFrameworkCore.AbpDbContext.SaveChanges() in
D:\Github\aspnetboilerplate\src\Abp.EntityFrameworkCore\EntityFrameworkCore\AbpDbContext.cs:line
198 at
Abp.Zero.EntityFrameworkCore.AbpZeroCommonDbContext`3.SaveChanges() in
D:\Github\aspnetboilerplate\src\Abp.ZeroCore.EntityFrameworkCore\Zero\EntityFrameworkCore\AbpZeroCommonDbContext.cs:line
154 at
Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.SaveChangesInDbContext(DbContext
dbContext) in
D:\Github\aspnetboilerplate\src\Abp.EntityFrameworkCore\EntityFrameworkCore\Uow\EfCoreUnitOfWork.cs:line
159 at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.SaveChanges()
in
D:\Github\aspnetboilerplate\src\Abp.EntityFrameworkCore\EntityFrameworkCore\Uow\EfCoreUnitOfWork.cs:line
60 at
MyCompany.MyProject.Business.Services.Tests.TestAppService.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__23.MoveNext()
INFO 2018-02-28 18:10:09,873 [26 ]
etCore.Mvc.Internal.ObjectResultExecutor - Executing ObjectResult,
writing value Microsoft.AspNetCore.Mvc.ControllerContext. INFO
2018-02-28 18:10:09,922 [26 ]
ore.Mvc.Internal.ControllerActionInvoker - Executed action
MyCompany.MyProject.Business.Services.Tests.TestAppService.DeleteTest
(MyCompany.MyProject.Business.Services) in 3940.4091ms INFO
2018-02-28 18:10:10,158 [26 ]
soft.AspNetCore.Hosting.Internal.WebHost - Request finished in
4037.4507ms 500 application/json; charset=utf-8
Note: It should delete the entry from Test and Test2 tables.
Update
The below anwer works pretty well but I have some specific requirement. Test Entity Id is being referred in other tables like TestTest2, TestTest3, TestTest4, TestTest5. When I delete a record from Test table, it should delete from all tables. But I also need to call the other dependent tables ( for example TestTest2, TestTest3, TestTest4, TestTest5) Delete method to do some extra cleanup specific to that entity (for example TestTest2, TestTest3, TestTest4, TestTest5).
TestRepository
public async Task DeleteTest(EntityDto input)
{
await DeleteAsync(input.Id);
_TestTest2Repository.Delete(x => x.TestId == input.Id);
_TestTest3Repository.Delete(x => x.TestId == input.Id);
_TestTest4Repository.Delete(x => x.TestId == input.Id);
_TestTest5Repository.Delete(x => x.TestId == input.Id);
}
From the documentation on Cascade Delete:
For optional relationships: ClientSetNull (default)
- Effect on dependent/child in database: None
You have to configure the delete behavior using Fluent API in your DbContext:
modelBuilder.Entity<TestTest2>()
.HasOne(t => t.Test)
.WithMany()
.OnDelete(DeleteBehavior.Cascade);

How can f System.Data.Entity.Internal.InternalContext.SaveChanges()

I have a windows service that call a Web Service, then stored the information in my t-sql database. In my pc this service works, but in another pc with the same database I have this error:
[16:06:00] Teresa Gabriele: Errore saveLocalActivity: in System.Data.Entity.Internal.InternalContext.SaveChanges()
in System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
in System.Data.Entity.DbContext.SaveChanges()
in GestoreService.Manager.Impl.AttivitaManagerImpl.saveLocalActivity(LOCAL_PE_Attivita attivita, Boolean saving) in c:\Users\michele.castriotta\Source\Workspaces\Omniacare\software\exercise platform\GestoreService\GestoreService\Manager\Impl\AttivitaManagerImpl.cs:riga 25
[16:06:52] Teresa Gabriele: Errore isAttivitaXMedicoExist: in System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
in System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
in System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
in System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
in System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
in System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass57.<ExecuteStoreCommand>b__56()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass57.<ExecuteStoreCommand>b__55()
in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
in System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
in System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
in System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
in GestoreService.Manager.Impl.AttivitaManagerImpl.inserAttivitaXMedico(Int32 idAttivita, String codiceFiscaleOperatoreMedico, String username) in c:\Users\michele.castriotta\Source\Workspaces\Omniacare\software\exercise platform\GestoreService\GestoreService\Manager\Impl\AttivitaManagerImpl.cs:riga 192
This is the code:
_db.LOCAL_PE_Attivita.Add(attivita);
int result = _db.SaveChanges(); //LINE 25
if (result > 0)
return true;
The Question is unclear, but I think that error is not in the code.
The log tell that error is in save on DB, but if this application work only on your pc I think (probably) that related to different version of DB.
checks whether this is the problem

Large bulk inserts cause transaction aborts or timeouts

Problem
When doing a bulk insert with several hundred thousand rows over two databases (programmatically, same instance, same schema) and about 17 tables per database, I nearly always receive a Transcaction Aborted or a Timeout Expired exception.
How
Using a EntityFramework 6 data context, I run a SqlCommand on the database.
using (var tran = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
context.Database.ExecuteSqlCommand(
"BULK INSERT " + table +
" FROM '" + Directory +
table + ".csv' WITH ( DATAFILETYPE = 'widechar', FIRSTROW = 2, FIELDTERMINATOR = '[TERM]', ERRORFILE = '" +
Logfile + DateTime.Now.ToString(#"yyyy-MM-dd") + "-R" + DateTime.Now.Second + DateTime.Now.Millisecond +
".txt', ROWTERMINATOR = '\n', KEEPNULLS, TABLOCK )");
tran.Complete();
}
Setting timeout values
To combat the problems I've been facing I have set both Command and Transaction timeouts to eighteen minutes. Either exception occurs long before said eighteen minutes have passed.
context.Database.CommandTimeout = 1080;
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.Timeout = TimeSpan.FromMinutes(18);
Full exceptions
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
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.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
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__DisplayClass59.<ExecuteStoreCommand>b__57()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at MyProject.Updaters.MSSQL.Csv.ImportCsvFiles() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 48
ClientConnectionId:fef47d9c-3e13-444f-939b-f9bd570abb36
+
System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.TimeoutException: Transaction Timeout
--- End of inner exception stack trace ---
at System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
at MyProject.Updaters.MSSQL.Csv.InsertCsvData() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 109
at MyProject.Updaters.MSSQL.Csv.ImportCsvFiles() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 74
What to do
I couldn't find any settings or similar within SQL Server (using SSMS). Any extra data you request to aid in providing an answer will be given.
Regarding timout during sql commands execution I would recommend you to set CommandTimeout via ObjectContext wrapped within DbContext:
((IObjectContextAdapter)context).ObjectContext.CommandTimeout = 1080;
This approach always worked for me.

Categories