EFMigrationsHistory table is empty - c#

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.

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

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.

Change data type in Model while preserving data (Entity Framework Core)

I'm learning the Entity Framework core, and I want to perform migrations, with changing the data type to custom one, while preserving the data.
I have the following model:
public class PageDataSections
{
[Key]
public int PageDataSectionId { get; set; }
public string DataText { get; set; }
}
which is converted to this one:
public class PageDataSections
{
[Key]
public int PageDataSectionId { get; set; }
public Translation DataText { get; set; }
}
While the class Translation is the following:
public class Translation
{
[Key]
public int TranslationId { get; set; }
public string TranslateEN { get; set; }
public string TranslateRU { get; set; }
public string TranslateUA { get; set; }
}
The migration that was created:
public partial class ChangeDataTextColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "DataTextTranslationId",
table: "PageDataSections",
nullable: true);
migrationBuilder.DropColumn(
name: "DataText",
table: "PageDataSections");
migrationBuilder.CreateIndex(
name: "IX_PageDataSections_DataTextTranslationId",
table: "PageDataSections",
column: "DataTextTranslationId");
migrationBuilder.AddForeignKey(
name: "FK_PageDataSections_Translations_DataTextTranslationId",
table: "PageDataSections",
column: "DataTextTranslationId",
principalTable: "Translations",
principalColumn: "TranslationId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.Sql(#"
INSERT INTO Translations(TranslateRU)
OUTPUT inserted.TranslationId
VALUES(SELECT DataText FROM PageDataSections)
INTO PageDataSections(DataTextTranslationId)
");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_PageDataSections_Translations_DataTextTranslationId",
table: "PageDataSections");
migrationBuilder.DropIndex(
name: "IX_PageDataSections_DataTextTranslationId",
table: "PageDataSections");
migrationBuilder.DropColumn(
name: "DataTextTranslationId",
table: "PageDataSections");
migrationBuilder.AddColumn<string>(
name: "DataText",
table: "PageDataSections",
nullable: true);
}
}
But Visual Studio is complaining with this one error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
INSERT INTO Translations(TranslateRU)
OUTPUT inserted.TranslationId
VALUES(SELECT DataText FROM PageDataSections)
INTO PageDataSections(DataTextTranslationId)
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near ')'.
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, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:14012b7c-68b2-4f43-9db1-b685734a2e37
Error Number:156,State:1,Class:15
Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
INSERT INTO Translations(TranslateRU)
OUTPUT inserted.TranslationId
VALUES(SELECT DataText FROM PageDataSections)
INTO PageDataSections(DataTextTranslationId)
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near ')'.
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, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.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.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:14012b7c-68b2-4f43-9db1-b685734a2e37
Error Number:156,State:1,Class:15
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near ')'.
Can anyone please help?
EDIT
After #Fabio reply, I have tried his code
migrationBuilder.Sql(#"
INSERT Translations (TranslateRU)
OUTPUT inserted.TranslationId INTO PageDataSections(DataTextTranslationId)
(SELECT DataText FROM PageDataSections)
");
and it gave me the following:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (231ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
INSERT Translations (TranslateRU)
OUTPUT inserted.TranslationId INTO PageDataSections(DataTextTranslationId)
(SELECT DataText FROM PageDataSections)
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'DataText'.
The target table 'PageDataSections' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK_PageDataSections_Translations_DataTextTranslationId'.
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, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:3224c672-8dbd-4690-8953-ee6108b65cff
Error Number:207,State:1,Class:16
Failed executing DbCommand (231ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
INSERT Translations (TranslateRU)
OUTPUT inserted.TranslationId INTO PageDataSections(DataTextTranslationId)
(SELECT DataText FROM PageDataSections)
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'DataText'.
The target table 'PageDataSections' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK_PageDataSections_Translations_DataTextTranslationId'.
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, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.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.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:3224c672-8dbd-4690-8953-ee6108b65cff
Error Number:207,State:1,Class:16
Invalid column name 'DataText'.
The target table 'PageDataSections' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK_PageDataSections_Translations_DataTextTranslationId'.
Which seems quite odd, because that column exists in the table:
UPDATE
This is how the foreign key is referenced
UPDATE
With this queries I have achieved some result, but it not modifies rows, but rather adds.. How to "Update" rather than "Insert"?
migrationBuilder.Sql(#"ALTER TABLE Pages DROP CONSTRAINT FK_Pages_PageDataSections_PageDataSectionId");
migrationBuilder.Sql(#"
INSERT Translations (TranslateRU)
OUTPUT inserted.TranslationId INTO PageDataSections(DataTextTranslationId)
SELECT DataText FROM PageDataSections;
");
migrationBuilder.Sql(#"ALTER TABLE Pages ADD CONSTRAINT FK_Pages_PageDataSections_PageDataSectionId FOREIGN KEY (PageDataSectionId) REFERENCES PageDataSections(PageDataSectionId)");
When the problem is complex, I prefer divide that.
For this migration, I will make 2 update :
Create and populate Translations table
Populate PageDataSections table
1) Create and populate Translations table
See the temporary column Translations.PageDataSectionId
public partial class Update1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "PageDataSectionOrigin",
table: "Translations",
nullable: true);
migrationBuilder.Sql(#"
INSERT INTO Translations (TranslateRU, PageDataSectionOrigin)
SELECT DataText, PageDataSectionId FROM PageDataSections
");
}
}
2) Populate PageDataSections table
See the temporary column is deleted.
public partial class Update2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DataText",
table: "PageDataSections");
migrationBuilder.AddColumn<int>(
name: "DataTextTranslationId",
table: "PageDataSections",
nullable: true);
migrationBuilder.Sql(#"
UPDATE PageDataSections SET DataTextTranslationId = (select TranslationId FROM Translations WHERE PageDataSectionOrigin=PageDataSectionId)
");
migrationBuilder.DropColumn(
name: "PageDataSectionOrigin",
table: "Translations");
}
}
You can combine this two update in one.
I don't know why, but EF have named the column PageDataSection.DataText to DataTextTranslationId. But you can replace easily this name.
I think your sql statement is invalid. Whole OUTPUT statement should be between INSERT and inserted values.
Besides you don't need VALUES keyword when you use result of anther query.
migrationBuilder.Sql(#"
INSERT Translations (TranslateRU)
OUTPUT inserted.TranslationId INTO PageDataSections(DataTextTranslationId)
(SELECT DataText FROM PageDataSections)
");

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

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