NHibernate 3.0 Linq query against <map> element instead of using HQL
I have a mapping that looks like this:
<class name="Record">
<map name="Values">
<key column="RecordFK"/>
<index column="FieldFK"/>
<element column="Value"/>
</map>
</class>
Translating this to English: a Record maps Fields to Values. In HQL, I can query this map, as follows:
from Record rec where rec.Values[:fieldFK] = :value
Is it possible to recreate this query using the new Linq provide开发者_高级运维r in NHibernate 3.0 instead of HQL? I tried the following code without success:
var records = session.Query<Record>()
.Where(rec => rec.Values[field.Key] == "foo");
This produced an error when NHibernate tried to interpret the dictionary accessor:
System.NotSupportedException: System.String get_Item(System.Int32)
Is there some way to "teach" NHibernate how to turn this C# expression into SQL?
NHibernate 3 does have a way to extend the provider to allow more expressions, check http://fabiomaulo.blogspot.com/2010/07/nhibernate-linq-provider-extension.html
However, this looks like something that should be supported. My suggestion is that you create a ticket at http://jira.nhforge.org with a failing test case.
If you're feeling like doing a little bit more, you can dive into https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Linq and create a patch. That will make things faster.
Update (2010-12-04): My patch has been merged into the trunk. This scenario is now supported (you can compile from source, or wait a few days for the final release)
NHibernate makes queries pretty simple with CreateCriteria as well. Heres an example:
var records = session.CreateCriteria<Record>()
.Add(Restrictions.Eq("Key", "foo)
.List<Record>();
But NHibernate does have a Linq provider that works as well. I'm not sure what Values[field.Key]
but thats probably whats throwing the error. Ideally you should be selecting a "Column" to compare against "foo".
精彩评论