Title

Tuesday, 20 January 2015

LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String, System.StringComparison)' method


I have executed a linq query by using Entityframework like below

GroupMaster getGroup = null;  getGroup = DataContext.Groups.FirstOrDefault(item => keyword.IndexOf(item.Keywords,StringComparison.OrdinalIgnoreCase)>=0 && item.IsEnabled)

when executing this method I got exception like below

LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String, System.StringComparison)' method, and this method cannot be translated into a store expression.

Contains() method by default case sensitive so again I need to convert to lower.Is there any method for checking a string match other than the contains method and is there any method to solve the indexOf method issue?

Answer

Instead you can use for lowering the cases this method below:

var lowerCaseItem = item.ToLower();

If your item is of type string. And this might get you through that exception.

Answer2

The IndexOf Method Of string class will not recognized by Entity framework, Please replace this function with SQLfunction or Canonical functions

You can also take help from here or may be here

You can use below code sample.

DataContext.Groups.FirstOrDefault(item => System.Data.Objects.SqlClient.SqlFunctions.CharIndex(item.Keywords, keyword).Value >=0 && item.IsEnabled)

Answer3

Erik Funkenbush' answer is perfectly valid when looking at it like a database problem. But I get the feeling that you need a better structure for keeping data regarding keywords if you want to traverse them efficiently.

Note that this answer isn't intended to be better, it is intended to fix the problem in your data model rather than making the environment adapt to the current (apparently flawed, since there is an issue) data model you have.

My main suggestion, regardless of time constraint (I realize this isn't the easiest fix) would be to add a separate table for the keywords (with a many-to-many relationship with its related classes).

[GROUPS] * ------- * [KEYWORD]

This should allow for you to search for the keyword, and only then retrieve the items that have that keyword related to it (based on ID rather than a compound string).

int? keywordID = DataContext.Keywords.Where(x => x.Name == keywordFilter).Select(x => x.Id).FirstOrDefault();    if(keywordID != null)  {   getGroup = DataContext.Groups.FirstOrDefault(group => group.Keywords.Any(kw => kw.Id == keywordID));  }

But I can understand completely if this type of fix is not possible anymore in the current project. I wanted to mention it though, in case anyone in the future stumbles on this question and still has the option for improving the data structure.

No comments:

Post a Comment