Entity Framework Case Sensitive Query

橙三吉。 提交于 2020-01-05 03:49:10

问题


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:

  1. change Key data type to varchar

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!