3

I am using Nhibernate with SQL server 2008.

I am trying to execute the following code:

        var localization = session.QueryOver<T>()
            .Where(idFilter).AndRestrictionOn(x => x.Language.IETFTag).IsLike(tag + "%").SingleOrDefault();

However, I get an exception on that line that says nhibernate cannot resolve property Language.IETFTag (or something to that effect).

I have tried using JoinQueryOver() but then it complains that I have multiple correlations in the FROM clause or something weird like that. It simply feels like I am doing something very wrong. How can I do what I want?

I have the following mapping:

internal class LocalizationMapping : ClassMap<Localization>
{
    public LocalizationMapping()
    {
        UseUnionSubclassForInheritanceMapping();
        Id(x => x.Id).GeneratedBy.HiLo("HiLo", "NextHi", "1000");
        References(x => x.Language);
    }
}

internal class LanguageMapping : ClassMap<Language>
{
    public LanguageMapping()
    {
        Id(x => x.Id);
        Map(x => x.DefaultName);
        Map(x => x.IETFTag);
    }
}

internal class ArticleLocalizationMapping : SubclassMap<ArticleLocalization>
{
    public ArticleLocalizationMapping()
    {
        Map(x => x.Name);
        Map(x => x.Description);
        References(x => x.Article);
    }
}
Max
  • 4,345
  • 8
  • 38
  • 64

1 Answers1

8

You need to previously do a join to the "Language" table using aliases. The complete query should be:

Language language = null;

var localization = session.QueryOver<Localization>()
            .JoinAlias(x => x.Language, () => language)
            .Where(idFilter)
            .AndRestrictionOn(() => language.IETFTag).IsLike(tag, MatchMode.End)
            .SingleOrDefault();

More info at: http://nhforge.org/blogs/nhibernate/archive/2009/12/17/queryover-in-nh-3-0.aspx

Also, the "IsLike" method accepts a second arg with the matching type. I took the liberty to update your instruction with it.

psousa
  • 6,676
  • 1
  • 32
  • 44
  • I had some hard time trying to solve the same problem a few weeks ago, and what you suggested worked for me. – Ilya Kogan Apr 27 '11 at 03:31
  • Thanks man. :) Inspecting Expression leads to somewhat esoteric code! But beautiful in it's own right. What I'm worried about though, what does this do to my SQL? Since I need an alias, does it mean that it joins/selects two times against the Language table? – Max Apr 27 '11 at 09:37
  • You're welcome :). Regarding your question, it only joins once with the Language table – psousa Apr 27 '11 at 12:47