问题
I have a table that named Post
which has a column named key
:
Id | Key | Title
--------------------
1 | WM | First
--------------------
2 | wm | Second
As you can see the first key
value of a Post
is WM
(Uppercase) and the second key
value is wm
(lowercase).
When I execute the query with following code:
var post = await _posts.Where(o => o.Key == key).Select(o => new
{
id = o.Id,
title = o.Title
}).SingleOrDefaultAsync();
I pass the key
with a value (wm and WM) but get one result. The second one (wm).
I've searched for the solution and found this question
and this answer. After I tried to use answer and implement [CaseSensitive]
data annotation when I search for wm
I get back the first post and when I search for WM
I get null
.
How can I solve this and get an adequate post with key?
Update: Generated SQL Query:
SELECT [Limit1].[C1] AS [C1],
[Limit1].[Id] AS [Id],
[Limit1].[Title] AS [Title]
FROM (SELECT TOP (2) [Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
1 AS [C1]
FROM [dbo].[Posts] AS [Extent1]
WHERE ([Extent1].[Key] = 'wm' /* @p__linq__0 */)
OR (([Extent1].[Key] IS NULL)
AND ('wm' /* @p__linq__0 */ IS NULL))) AS [Limit1]
回答1:
I Solve this issue with same change:
change
Key
data type tovarchar
and execute SQL Query with
SqlQuery<T>
:var post = await _uow.Database .SqlQuery<PostUrlDto>( "SELECT Id , Title FROM Posts WHERE [Key] = @postkey COLLATE SQL_Latin1_General_CP1_CS_AS", new SqlParameter("postkey", postkey)).SingleOrDefaultAsync()
来源:https://stackoverflow.com/questions/46239476/entity-framework-case-sensitive-query