1

对于我正在处理的项目,我需要查询 Nhibernate 中映射字典的值。就像是

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

我已经尝试了几件事,但我无法弄清楚我该怎么做。这就是我所拥有的。

实体

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; }
    }
}

它在 EntityWithDictionary.Dictionary 中,我想调查这些值。

映射:

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();
}

这是我迄今为止尝试过的:

查询查询:

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

这导致以下 sql 语句 =>

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 ]

在这个查询中,NHibernate 选择使用 2 个别名(dictionary1_,dictionary3_),其中只创建了 1 个(dictionary3_)。

标准

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

这会生成与 queryover 相同的 sql 查询,但问题与结果相同。

我知道这在 hql 中是可能的,但是我如何使用 ICriteria 的 QueryOver 来做到这一点?

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

1 回答 1

0

如果 Linq 是一个选项,请使用

session.Query<EntityWithDictionary>()
    .Where(f => f.Dictionary["key"] == "value")
    .ToList();
于 2012-07-31T13:30:11.083 回答