LINQ to NHibernate - compare guid with string

return queryable.Where(version => version.Id.ToString().Contains(searchKey)); 

This line will cause "ToString is not supported by exception."

Purpose: to create a search query that will compare a string, int, GUID with the keyword string.

Thanks for any help.

+4
source share
4 answers

Not tested, but before the request, you could try to create your Guid-to-be-search object.

 Guid searchGuid; try { searchGuid = Guid.Parse(searchKey); } catch (System.FormatException) { // Handle invalid search key } return queryable.Where(version => version.Id == searchGuid); 

Edit:

Not tested (sorry, again), but afaik NHibernate.Linq can translate type conversion statements into equivalent SQL Cast functions. Perhaps this should work:

 return queryable.Where(version => (string)version.Id == searchGuid); 

I am not sure about C # sintax. In VB.NET, I would write something like:

 Return queryable.Where(Function(version) CType(version.Id,String) = searchGuid) 
+3
source

You cannot do this directly with LINQ (you need to extend the LINQ provider, which is nontrivial)

This, however, is easy to do with all the other query methods that NHibernate has.

Here is an example with QueryOver:

 return session.QueryOver<YourEntity>() .Where(Restrictions.Like( Projections.Cast(NHibernateUtil.String, Projections.Property<YourEntity>( version => version.Id)), searchKey, MatchMode.Anywhere)) 
+1
source

The best way to compare is

 return queryable. Where(version => (String.Compare(version.Id.ToString(),searchkey, true)==0); 

Note: Here I see searchkey as anc string converting version.Id guid in string and using String.Compare and string and ignoring case in string, putting true in comparison method

0
source

Here is the answer for frame 4.5 at least ...

  Version Ver = null; foreach (Version V in Versions) { Guid g = V.ID; if (string.Compare(g.Value.ToString(), searchkey)) { Ver = V; break; } } OR in LINQ Version Ver = Version.Where(v => v.ID.Value.ToString == searchkey).FirstOrDefault; //Use found Ver ;-) 
0
source

All Articles