Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

linq - How do I query an integer column for "starts with" in Entity Framework?

I have a column that's defined as an integer in EF (Code First). I want to search it using "starts with." Now, I can do this:

Where(x => SqlFunctions.StringConvert((double)x.AccountNumber).StartsWith(searchTerm))

However, SqlFunctions.StringConvert() gets translated to the T-SQL function STR(), which left-pads the result for reasons which are beyond my comprehension.

Also, I can't use string.TrimStart() because it's not supported by the Entity Framework.

Can anyone lend any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Trim() and TrimStart() work in LINQ to Entities, so you can use:

Where(x => SqlFunctions.StringConvert((double)x.AccountNumber)
    .TrimStart().StartsWith(searchTerm))

TrimStart translates into LTRIM in SQL. With searchTerm = 123 for example you get something like:

WHERE LTRIM(STR( CAST( [Extent1].[AccountNumber] AS float))) LIKE N'123%'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...