My query is like this:
var list = context.Items
.Where(i => i.Title.StartsWith(searchValue) ||
(i.Title + string.format("{0}prep", i.OrderNumber))
.StartsWith(searchValue))
.ToList();
But I am gettings exception - object not set to the instance of the object.
I also tried to add .AsEnumerable after .Where but doesn't work.
Without AsEnumerable I am getting:
LINQ to Entities does not recognize the method 'System.String
Format(System.String, System.Object)' method, and this method cannot
be translated into a store expression.
What I did wrong here?
What I did wrong here?
The answer is in the exception message:
LINQ to Entities does not recognize the method System.String Format(System.String, System.Object) method, and this method cannot be translated into a store expression.
In other words, string.Format method is not supported because it cannot be translated to SQL query.
Fortunately string concatenation is supported, so you can use this instead:
var list = context.Items.Where(i => i.Title.StartsWith(searchValue)
|| (i.Title + i.OrderNumber + "prep").StartsWith(searchValue))
.ToList();
Related
I'm getting an exception when trying to use TruncateTime() in my linq expresion
and I'm not sure why?
Here is my statement
var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();
var yogaEvents = yogaProfile.RegisteredEvents.Where(j =>
(j.EventStatus == YogaSpaceEventStatus.Active || j.EventStatus == YogaSpaceEventStatus.Completed)
&& DbFunctions.TruncateTime(j.UTCEventDateTime) > DbFunctions.TruncateTime(yesterday)
&& DbFunctions.TruncateTime(j.UTCEventDateTime) <= DbFunctions.TruncateTime(todayPlus30)
).ToList();
and here is the exception
System.NotSupportedException: This function can only be invoked from LINQ to Entities.
at System.Data.Entity.DbFunctions.TruncateTime(Nullable`1
dateValue)
at
YogaBandy2017.Services.Services.YogaSpaceService.<>c__DisplayClass9_1.b__1(YogaSpaceEvent
j) in
C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\Yogabandy2017.Services\Services\YogaSpaceService.cs:line
256
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List'1..ctor(IEnumerable`1
collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at
YogaBandy2017.Services.Services.YogaSpaceService.GetUpcomingAttendEventCounts(String
userId) in
C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\Yogabandy2017.Services\Services\YogaSpaceService.cs:line
255
at
YogaBandy2017.Controllers.ScheduleController.GetEventCountsForAttendCalendar()
in
C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\YogaBandy2017\Controllers\ScheduleController.cs:line
309
System.NotSupportedException: This function can only be invoked from LINQ to Entities.
You have this exception because the result of yogaProfile variable is not an IQueryable which is used by Linq To Entities to perform query on server side. To make your variable to be an IQueryable you need to remove the extension method First() you use on the query at the end and replace it with Take(1).
So instead of
var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();
You should have this:
var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).Take(1);
Note that with the first statement you are dealing with Linq To Objects when you perform Linq on the variable. By removing First() extension method and replace it with Take() extension method you'll perform Linq To Entites.
I am using this code:
query = String.IsNullOrEmpty(options.PhraseNum) ?
query :
query.Where(w => w.PhraseNum == Convert.ToInt32(options.PhraseNum));
However I get an error:
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
Is there a way I can do this in LINQ and if not how can I convert outside of this and have the conversion not cause an exception if the string is not null?
Only modify query if the string can be parsed to an int, which is an implicit check if it isn't null or empty:
if (int.TryParse(options.PhraseNum, out var phraseNum))
{
query = query.Where(w => w.PhraseNum == phraseNum);
}
Before C# 7 the syntax was
int phraseNum;
if (int.TryParse(options.PhraseNum, out phraseNum))
etc.
It looks like LINQ is trying to evaluate the expression Convert.ToInt32(options.PhraseNum) on the server side as part of the WHERE clause.
Redo the code so that the variable is cast explicitly on the client-side outside the query expression:
Int32 phrase_num = String.IsNullOrEmpty(options.PhraseNum) ? 0 : Convert.ToInt32;
query = String.IsNullOrEmpty(options.PhraseNum) ? query : query.Where(w => w.PhraseNum == phrase_num);
Or for a tidier approach overall:
if(!String.IsNullOrEmpty(options.PhraseNum))
{
Int32 phrase_num = Convert.ToInt32(options.PhraseNum);
query = query.Where(w => w.PhraseNum == phrase_num);
}
I think that should resolve the problem and preserve the intended program logic.
EDIT: I'd endorse Gert Arnold's approach above if you are using the latest C# version, where out parameters can be declared inline in the TryParse method call itself.
I have this code:
public static bool ContainEx<T>(this IQueryable<T> query, System.Linq.Expressions.Expression<System.Func<T, bool>> expression)
{
return query.Any(expression);
}
If I use that:
return bonusesWhereSearch.WhereEx(x => userBonusesWhereSearch.ContainEx(y => y.Bonus_Id == x.Id));
I get this error message:
System.NotSupportedException: LINQ to Entities does not recognize the
method 'Boolean
ContainEx[Bonus](System.Linq.IQueryable`1[SDataEntities.Bonus],
System.Linq.Expressions.Expression`1[System.Func`2[SDataEntities.Bonus,System.Boolean]])'
method, and this method cannot be translated into a store expression.
and if I use Any:
return bonusesWhereSearch.WhereEx(x => userBonusesWhereSearch.Any(y => y.Bonus_Id == x.Id));
that does work.
Problem here is, that entity framework doesn't execute ContainEx, but tries to translate this method into SQL. And since this is custom method translation fails. If you use Any directly, it is correctly translated to SQL equivalent.
Following code block throws error.
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
db.tbOnIgmHawbDetails
.Where(s => !db.tbImpoExaminations.Any(x => x.Hawb.ToString() == s.Hawb) && s.AwbNo == p)
.Select(s => s.Hawb).ToList();
Any suggestion? why this happen and what is the solution?
.ToString() is supported properly going forward with EF 6.1: http://blogs.msdn.com/b/adonet/archive/2014/03/17/ef6-1-0-rtm-available.aspx
You could try with SqlFunctions.StringConvert... Use the decimal conversion:
SqlFunctions.StringConvert((decimal)p.x.Hawb).TrimLeft() == ...
(the TrimLeft is necessary because the STR function of SQL will right align the number)
If s.Hawb is already string type (the error message suggests so), then remove the part .ToString() from your query.
The reason for it is that in LINQ2SQL, you can only use those language constructs that can be translated into SQL. For example, if you try to use RegEx in your C# expression, then SQL does not have a corresponding construct for RegEx, and thus LINQ cannot translate and execute your query.
Easily add .AsEnumerable() before the .ToString() and those methods that L2E doesn't support:
var asen = db.tbOnIgmHawbDetails.AsEnumerable();
var result = asen.Where(s => !asen.Any(x => x.Hawb.ToString() == s.Hawb) && s.AwbNo == p)
.Select(s => s.Hawb).ToList();
That should works. However if not, try to perform your query by linq-to-objects syntax:
var result = from a in asen
where ...
select ...;
do not use ToString
just use like
x.Hawb + "" == s.Hawb
My code:
i f(!string.IsNullOrWhiteSpace(gender))
if (gender == "NULL")
predicate = predicate.And(x => string.IsNullOrWhiteSpace(gender));
else
predicate = predicate.And(x => x.Gender == gender);
When gender is NULL and when I am executing the flowing line:
var filteredUsers = _personExtendedRepository.GetMany(predicate).ToList();
an error occurs:
"LINQ to Entities does not recognize the method 'Boolean IsNullOrWhiteSpace(System.String)' method, and this method cannot be translated into a store expression."
Note:
When I am executing the following line in SQL Server Management Studio:
SELECT * FROM UVW_Sample WHERE Gender IS NULL
Records are displaying. Please help how to solve this issue.
LINQ-to-Entities is limited in what it can do, as it translates your expression to SQL, and it doesn't know how to translate string.IsNullOrWhiteSpace to SQL. It also doesn't know how to translate .ToString() to SQL.
What you need to do is perform the translation outside LINQ-to-Entities. In your case, your predicate should be:
x=>x==null || x.Trim()==""
string.IsNullOrWhiteSpace cannot be translated into SQL, so if you want to check whether column is null use something like:
predicate = predicate.And(x => x.Gender == null);