SQL Server localDB could not create file - c#

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...

Related

FindByNameAsync throws a Drop Drop Database error in Entity Framework

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.

Incorrect syntax near 'ENTUserAccount'

Incorrect syntax near 'ENTUserAccount'.
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.Data.SqlClient.SqlException: Incorrect syntax near 'ENTUserAccount'.
Source Error:
Line 76: " WHERE " + fieldName + " = {0}" +
Line 77: " AND " + fieldNameId + " <> {1}";
Line 78: var result = db.ExecuteQuery(sql, new object[] { value, id });
Line 79: List list = result.ToList();
Line 80: return (list[0].DuplicateCount > 0);
Source File: c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs Line: 78
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'ENTUserAccount'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1753346
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5295154
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +1306
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +118
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +342
System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters) +83
System.Data.Linq.DataContext.ExecuteQuery(String query, Object[] parameters) +254
V2.PaidTimeOffDAL.Framework.ENTUserAccountData.IsDuplicate(HRPaidTimeOffDataContext db, String tableName, String fieldName, String fieldNameId, String value, Int32 id) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs:78
V2.PaidTimeOffDAL.Framework.ENTUserAccountData.IsDuplicateWindowsAccountName(HRPaidTimeOffDataContext db, Int32 userAccountId, String windowsAccountName) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs:69
V2.PaidTimeOffBLL.Framework.ENTUserAccountEO.Validate(HRPaidTimeOffDataContext db, ENTValidationErrors& validationErrors) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTUserAccountEO.cs:66
V2.PaidTimeOffBLL.Framework.ENTUserAccountEO.Save(HRPaidTimeOffDataContext db, ENTValidationErrors& validationErrors, Int32 userAccountId) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTUserAccountEO.cs:23
V2.PaidTimeOffBLL.Framework.ENTBaseEO.Save(ENTValidationErrors& validationErrors, Int32 userAccountId) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTBaseEO.cs:49
Administration_User.Master_SaveButton_Click(Object sender, EventArgs e) in c:\Program Files\IIS\PaidTimeOffUI1\Administration\User.aspx.cs:27
PaidTimeOffEditPage.btnSave_Click(Object sender, EventArgs e) in c:\Program Files\IIS\PaidTimeOffUI1\PaidTimeOffEditPage.master.cs:27
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

DbMigration.SqlFile generate SqlException (0x80131904): Transaction context in use by another session

I have created database migration and in Up method I want to execute sql files with SqlFile method. Each of files contains 2 statements: first drop procedure if exists and second one is create procedure. Both statements finishes with GO. Here is exception, which I got when tried to apply migration:
System.Data.SqlClient.SqlException (0x80131904): Transaction context in use by another session.
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.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 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__DisplayClassc.<Update>b__b()
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.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:923d4c55-19e7-4c7d-b2b6-48c710d2264a
Error Number:3910,State:2,Class:16
Transaction context in use by another session.
Stored procedures containce requests to linked server, can it be the reason of issue?
EDIT
Up method pretty simple:
public override void Up()
{
SqlFile(#"Sql\sp_MergeData.sql");
}
I have investigated that is is related to code inside SP. I've tried to make it as simple as possible and I get no errors after that. SP with merge statement and linked server selects.
EDIT 2
I have found that reason of this issue is creating synonym from linked server table so before executing SP code there is no in database. Is there a workaround?
EDIT 3
Issue does not exists on machine of my team member so I leave it as it is for now.
Fixed with passing true to the not mandatory parameter suppressTransaction

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

Deleting an object in asp.net mvc doesn't work

In a controller an object is built and saved into the database.
In the same controller action, I created another object of a different type and saved it (Class SecondType also includes an ID):
cDb.SecondType.Add(new SecondType { Designation = "test" });
cDb.SaveChanges();
That works. When looking at index (I created the classic create, delete,... views using the scaffolding options) or detail view I can see this object and I also can modify it. But, if I click on delete, it shows me the first view where I have to confirm the deletion and after pressing the submit button it returns a DbUpdateException without any further information at the SaveChanges command:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SecondType secondType = db.SecondTypes.Find(id);
db.SecondTypes.Remove(secondType);
db.SaveChanges();
return RedirectToAction("Index");
}
I don't know why this happens and I would be very thankful if you have any ideas to fix this.
This is what I could copy:
System.Data.Entity.Infrastructure.DbUpdateException ist aufgetreten.
HResult=-2146233087
Message=Fehler beim Aktualisieren der Einträge (= Error while updating the entries). Weitere Informationen finden Sie in der internen Ausnahme.
Source=EntityFramework
StackTrace:
bei System.Data.Entity.Internal.InternalContext.SaveChanges()
bei System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
bei System.Data.Entity.DbContext.SaveChanges()
bei Irgendwas.Controllers.SecondTypeController.DeleteConfirmed(Int32 id) in c:\Users\username\Documents\Visual Studio 2012\Projects\Irgendwas\Irgendwas\Irgendwas\Controllers\SecondTypeController.cs:Zeile 113.
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=Fehler beim Aktualisieren der Einträge. Weitere Informationen finden Sie in der internen Ausnahme.
Source=System.Data.Entity
StackTrace:
bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
bei System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
bei System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
bei System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Die DELETE-Anweisung steht in Konflikt mit der REFERENCE-Einschränkung 'FK_dbo.ThirdTypes_dbo.Second_SecondType_ID'. Der Konflikt trat in der 'Irgendwas.Models.SecondTypeContext'-Datenbank, Tabelle 'dbo.ThirdTypes', column 'SecondType_ID' auf.
Die Anweisung wurde beendet.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=547
Procedure=""
Server=.\SQLEXPRESS
State=0
StackTrace:
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.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
bei System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
bei System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
bei System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
My german is a bit rough but I think you have entries in your dbo.ThirdTypes table that reference the entry you try to delete from the dbo.SecondTypes table.
Try to remove all dbo.ThirdTypes entries that reference the dbo.SecondTypes before you remove the secondType entry and call SaveChanges().
Like so:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SecondType secondType = db.SecondTypes.Find(id);
foreach (var thirdType in secondType.ThirdTypes)
{
db.ThirdTypes.Remove(thirdType);
}
db.SecondTypes.Remove(secondType);
db.SaveChanges();
return RedirectToAction("Index");
}
You can also enable Cascade Delete on the relation in your database.

Categories