Daniel
Daniel

Reputation: 1044

SQL conversion error when statement executed from Entity Framework, but works fine when corresponding sql is executed

I have a piece of code where I add objects and delete another one from the object context. When saving changes on the object context, it raises the following SQL Exception:

Failed converting nvarchar value 'KV Oberaargau136' to data type int

Of course 'KV Oberaargau136' can't be converted to an int value, the trouble is I don't know how that string got there. The only place that string can come from is from the following bit of code:

History h = new History()
{
    idTableRef = rpo.idOA,
    tableRef = "RelPersonOrganism",
    date = now,
    idResponsible = entities.getUserOA().id,
    data = "<delete><organism><name><![CDATA[%name%]]></name><id>%id%</id></organism></delete>"
        .Replace("%name%", organism.defaultName)
        .Replace("%id%", organism.idOA.ToString())
};

Where History is an entity and data is a string (actually xml data type on the SQL Server)

So I've tried to see with the SQL Profiler what SQL statement could provoke that exception and here is the part of the trace which throws the exception:

RPC:Starting        exec sp_executesql N'insert [dbo].[History]([tableRef], [idTableRef], [date], [idResp...
SQLTransaction
Exception           Error: 245, Severity: 16, State: 1
User Error Message  Conversion failed when converting the nvarchar value 'KV Oberaarau136' to data type int.
SQLTransaction
SP:Completed        insert [dbo].[History]([tableRef], [idTableRef], [date], [idResponsible], [data]) v...
RPC:Completed       exec sp_executesql N'insert [dbo].[History]([tableRef], [idTableRef], [date], [idRespon...

where the complete SQL statement (which shows 3 times in the above trace) is:

EXEC sp_executesql
  N'insert [dbo].[History]([tableRef], [idTableRef], [date], [idResponsible], [data])
values (@0, @1, @2, @3, @4)
select [id]
from [dbo].[History]
where @@ROWCOUNT > 0 and [id] = scope_identity()',
  N'@0 nvarchar(255),@1 int,@2    datetime2(7),@3 int,@4 nvarchar(max) ',
  @0=N'RelPersonOrganism',
  @1=1255,
  @2='2013-01-11     12:35:18.4984109',
  @3=1,
  @4=N'<delete><organism><name><![CDATA[KV Oberaargau]]></name><id>136</id></organism></delete>'

So by looking at the trace, I concluded that this SQL Statement was to be incriminated, although it didn't seem wrong at all to me. So I tried to execute it in the SQL Server Management Studio and it worked perfectly fine without error...

So what could be triggering that error ?

Upvotes: 0

Views: 612

Answers (1)

Martin Smith
Martin Smith

Reputation: 453057

I can't see any way the query you posted can cause that error message directly either.

So check if you have any triggers or computed columns that parse the XML and might be the cause.

Upvotes: 1

Related Questions