Skip to content

Update of column data fails in EFCore 10 #37423

Closed as duplicate
Closed as duplicate

Description

@wmahalek

Bug description

Code that works just fine in EFCore 9 now fails with the following error message:

Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'EFCore' to data type int.

The produces SQL statement looks just fine and can be executed manually in the database without a problem.

Might this somehow be related to the introduction of "LogCommandText" in src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs?

Your code

var user = await _cardDbContext
            .User.Where(u => u.Id == userId)
            .FirstOrDefaultAsync(cancellationToken);

        if (user == null)
        {
            throw new BusinessException(Errors.UserNotFound, Errors.UserNotFound);
        }

        user.Name = userName;

        await _cardDbContext.SaveChangesAsync(cancellationToken);

Stack traces

2025-12-29 08:51:19 [ERR] Failed executing DbCommand (7ms) [Parameters=[@p1='811', @p0='Test' (Nullable = false) (Size = 30)], CommandType='Text', CommandTimeout='30']
SET IMPLICIT_TRANSACTIONS OFF;
SET NOCOUNT ON;
UPDATE [Mitarbeiter] SET [Name] = @p0
WHERE [KartenNr] = @p1;
SELECT @@ROWCOUNT;
2025-12-29 08:51:19 [ERR] An exception occurred in the database while saving changes for context type 'BB3.Cards.Infrastructure.CardDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'EFCore' to data type int.
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:fbdd7fe9-f1f0-40c1-a58e-0d1e0358fcc2
Fehlernummer (Error Number):245,Status (State):1,Klasse (Class):16
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChangesAsync(IList`1 entries, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)

Verbose output


EF Core version

10.0.1

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

.NET 10

Operating system

Windows 11

IDE

VSCode

Activity

  1. roji commented on Dec 29, 2025

    @roji
    Member

    @wmahalek I can't reproduce the problem. Please (always) submit a fully runnable code sample - the above is a partial snippet that isn't sufficient.

  2. wmahalek commented on Dec 29, 2025

    @wmahalek
    Author

    Please find attached the code sample that reproduces the problem. You will need to run the included CreateTestDB.sql on a SqlServer first to create the Test-DB. (I'm using 2022-latest SqlServer docker image.)

    The problems occurs in EFCore 10 with the history trigger but works without changes with EFCore 9. (see TestEFCore.csproj) Unfortunately I can't change the database code as it is used by other services.

    TestEFCore.zip

  3. roji commented on Dec 29, 2025

    @roji
    Member

    With EF 10, EF now populates the Application Name connection string parameter by default, to include versioning info about EF, SqlClient, etc. Your stored procedure appears to parse this information by selecting program_name from sys.dm_exec_sessions, and your parsing logic appears to be incompatible with the new values introduced by EF.

    You can either fix your parsing logic to be compatible with the EF values, or simply specify whatever Application Name you want via the connection string; the moment that's set to a non-empty value, EF will no longer overwrite it with its own value. I've verified that your program passes after doing this.

    Somewhat minimal repro used for experimentation
    await using var context = new CardDBContext();
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
    
    context.Database.ExecuteSqlRaw("CREATE SCHEMA hist;");
    context.Database.ExecuteSqlRaw(
        """
    CREATE TABLE [hist].[h_Mitarbeiter](
    	[HistZeitstempel] [datetime] NULL,
    	[HistHostname] [nvarchar](30) NULL,
    	[HistUsername] [nvarchar](30) NULL,
    	[HistAktion] [int] NULL,
    	[HistApp] [int] NULL,
    	[HistSQS] [int] NULL,
    	[KartenNr] [int] NULL,
    	[Name] [nvarchar](30) NULL
    ) ON [PRIMARY];
    """);
    
    context.Database.ExecuteSqlRaw(
        """
    CREATE FUNCTION [hist].[HistDaten]()
    RETURNS @Daten TABLE
    (
    	HistHostname	nvarchar(30),
    	HistSQS			int,
    	HistApp			int,
    	HistUsername	nvarchar(30)
    )
    AS
    BEGIN
    	declare @host_name		nvarchar(30),
    			@program_name	nvarchar(40),
    			@pos1			int,
    			@pos2			int,
    			@SQS			int,
    			@App			int
    
    	select @host_name = SUBSTRING(host_name, 1, 30),
    	       @program_name = SUBSTRING(program_name, 1, 40)
    	  from sys.dm_exec_sessions
    	 where session_id = @@SPID
    	;
    	set @pos1 = CHARINDEX('/', @program_name, 1)
    	if @pos1 > 0
    	begin
    		set @SQS = cast(SUBSTRING(@program_name, 1, @pos1 - 1) as int)
    		set @pos2 = CHARINDEX('/', @program_name, @pos1 + 1)
    		if @pos2 > 0
    		begin
    			set @App = cast(SUBSTRING(@program_name, @pos1 + 1, @pos2 - @pos1 - 1) as int)
    			set @program_name = SUBSTRING(@program_name, @pos2 + 1, 30)
    		end
    		else
    			set @program_name = SUBSTRING(@program_name, @pos1 + 1, 30)
    	end
    	else
    		set @program_name = SUBSTRING(@program_name, 1, 30)
    
    	RETURN
    END;
    """);
    
    context.Database.ExecuteSqlRaw(
        """
    CREATE TRIGGER [dbo].[Mitarbeiter_HistTrg] on [dbo].[Mitarbeiter]
       AFTER UPDATE, INSERT, DELETE
    AS
    BEGIN
    	INSERT INTO hist.h_Mitarbeiter (KartenNr, Name) SELECT KartenNr, Name FROM deleted, hist.HistDaten();
    END
    """);
    
    var user = context.Users.Add(new User { Id = 999, Name = "NoName" });
    context.SaveChanges();
    
    public class CardDBContext : DbContext
    {
        public DbSet<User> Users { get; set; } = default!;
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer("Server=localhost;Database=test;User=SA;Password=***;Connect Timeout=60;ConnectRetryCount=0;Trust Server Certificate=true;Application Name=foo")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<User>(entity =>
            {
                entity.ToTable("Mitarbeiter");
                entity.ToTable(t => t.HasTrigger("Mitarbeiter_HistTrg"));
                entity.HasKey(p => p.Id);
                entity.Property(p => p.Id).HasColumnName("KartenNr").HasColumnType("int").ValueGeneratedNever();
                entity.Property(p => p.Name).HasColumnName("Name").HasColumnType("nvarchar(30)");
            });
        }
    }
    
    public class User
    {
        public required int Id { get; set; }
        public required string Name { get; set; }
    }
  4. wmahalek commented on Dec 29, 2025

    @wmahalek
    Author

    This solved my problem. Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions