NHibernate QueryOver the values of a dictionary(map)

白昼怎懂夜的黑 提交于 2019-12-11 06:28:56

问题


For a project i'm working on, i need to query over the values of a mapped dictionary in Nhibernate. Something like

SELECT * FROM EntityWithDictionary WHERE EntityWithDictionary 
    in (select EntityFromDictionaryId FROM Dictionary where value = 'testvalue')

I've tried several things but I can't figure out how i can do it. Here is what i have.

Entity

public class EntityWithDictionary
{
    public virtual Guid Id { get; set; }
    public virtual string Description { get; set; }
    private IDictionary<string, string> _dictionary = new Dictionary<string, string>();
    public virtual IDictionary<string, string> Dictionary
    {
        get { return _dictionary; }
    }
}

It's in the EntityWithDictionary.Dictionary i want to investigate the values.

Mappings:

public EntityWithDictionaryMap()
{
    Id(s => s.Id);
    Map(s => s.Description);
    HasMany(m => m.Dictionary)
        .Table("`Dictionary`")
        .KeyColumn("EntityWithDictionaryId")
        .AsMap<string>("`Key`")
        .Element("`Value`")
        .LazyLoad()
        .Access.CamelCaseField(Prefix.Underscore)
        .Cascade.All();
}

This is what i've tried so far:

Queryover query :

EntityWithDictionary entityWithDictionary = null;
var result = session.QueryOver<EntityWithDictionary>(() =>entityWithDictionary)
        .JoinQueryOver(dictionary =>dictionary.Dictionary)
        .UnderlyingCriteria.Add(Restrictions.Eq("elements", "test")).List();

This results in the following sql-statement =>

SELECT this_.Id as Id0_0_, this_.Description as Descript2_0_0_ FROM
[EntityWithDictionary] this_ inner join [Dictionary] dictionary3_ on
this_.Id=dictionary3_.EntityWithDictionaryId WHERE dictionary1_.[Value] = @p0 ]

In this query NHibernate chooses the use 2 aliasses (dictionary1_, dictionary3_) where only 1 is created (dictionary3_).

ICriteria

ICriteria criteria = session.CreateCriteria<EntityWithDictionary>();
criteria("Dictionary").Add(Restrictions.Eq("elements", "testValue"));
var result = criteria.List();

This generates the same sql query as with queryover, with the same problem as result.

I know that this is possible in hql with something like, but how can i do this with QueryOver of ICriteria?

from EntityWithDictionaryId e where 'aDictionaryValue' in elements(m.Dictionary).

回答1:


if Linq is an option use

session.Query<EntityWithDictionary>()
    .Where(f => f.Dictionary["key"] == "value")
    .ToList();


来源:https://stackoverflow.com/questions/11683365/nhibernate-queryover-the-values-of-a-dictionarymap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!