3

I have to write linq to sql server between two tables,the related fields are in a different types. one is string(nvarchar) and the other is int.

here is my linq:

from je in a
join vP in b
on je.BaseRef  equals SqlFunctions.StringConvert((decimal) vP.DocEntry)

the result of the linq in sql was:

SELECT 
[Extent1].[Account] AS [Account]
FROM  [dbo].[a] AS [Extent1]
JOIN [dbo].[b] AS [Extent2] ON ([Extent1].[BaseRef] = (STR( CAST( [Extent2].[DocEntry] AS float)))) OR (([Extent1].[BaseRef] IS NULL) AND (STR( CAST( [Extent2].[DocEntry] AS float)) IS NULL))

that query return null because sql can not compare varchar and nvarchar. linq to entity translate sqlfunction.stringFormat to str('') and not to convert(nvarchar,''). how can I convert to nvarchar?

1 Answer 1

4

There is a work-around:

SqlFunctions.StringConvert((decimal) vP.DocEntry) + ""

This will translate to

(STR( CAST( [Extent2].[DocEntry] AS float))) + N''

which lifts the whole expression to nvarchar.

But I suspect that the comparison between char and nvarchar should not be a problem. The problem is more likely to be solved by trimming the conversion result:

SqlFunctions.StringConvert((decimal) vP.DocEntry).Trim()
Sign up to request clarification or add additional context in comments.

7 Comments

Hello ,Thanks for your reply. I tried it but it returned varchar.
Are you sure? I checked a similar query with SQL_VARIANT_PROPERTY( STR( CAST( CAST( xxx AS float)) + N'', 'BaseType'). It was nvarchar. But are you sure that a mismatch between char and nvarchar is the problem? They should compare equally.
hi gert, I tried it, also with the trim() and it was the same. sql can not compare nvarchar and varchar, sql can compare int and string without converting, but linq to entity does not pass build in this situation.
Char and nvarchar should compare just fine. Try SELECT CASE WHEN N'b' = CAST('b' AS char) THEN 1 ELSE 0 END (output: 1). It must be something else. Maybe you should show some sample data (including BaseRef and DocEntry).
when i run the query that I got from linq:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.