简体   繁体   中英

EFCore 3: How to compare string columns on server side

I want to effectively get results from this query.

// Get all people whose name starts with F or later alphabets

Select * from MyTable where PersonName >'F'

When i run this code using Entity Framework Core 3.0,

                 context.MyTable 
                 .Where(t=>  String.Compare(t.PersonName ,"F")>0);

I got error,

query could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

My current work around is to use FromSQL method and write my own sql. Is there any way to achieve the same using LINQ syntax?

From Microsoft's doc Where

The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly

You should call method ToList() or ToListAsync() after Where for forces immediate query evaluation

In your code

context.MyTable
             .TakeWhile(t => t.PersonName.First() > 'F')
             .ToList(); 

Best solution for

Get all people whose name starts with F or later alphabets

    context.MyTable
             .OrderBy(t => t.PersonName)
             .SkipWhile(t => t.PersonName.First() < 'F')
             .ToList();

Take care with Upper and lower case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM