问题描述
对于我正在进行的项目,我需要在 Nhibernate 中查询映射字典的值.类似的东西
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.
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 中,我想调查这些值.
It's in the EntityWithDictionary.Dictionary i want to investigate the values.
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:
EntityWithDictionary entityWithDictionary = null;
var result = session.QueryOver<EntityWithDictionary>(() =>entityWithDictionary)
.JoinQueryOver(dictionary =>dictionary.Dictionary)
.UnderlyingCriteria.Add(Restrictions.Eq("elements", "test")).List();
这导致以下 sql 语句 =>
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 ]
在此查询中,NHibernate 选择使用 2 个别名(dictionary1_、dictionary3_),其中仅创建 1 个(dictionary3_).
In this query NHibernate chooses the use 2 aliasses (dictionary1_, dictionary3_) where only 1 is created (dictionary3_).
ICriteria criteria = session.CreateCriteria<EntityWithDictionary>();
criteria("Dictionary").Add(Restrictions.Eq("elements", "testValue"));
var result = criteria.List();
这将生成与 queryover 相同的 sql 查询,与结果相同的问题.
This generates the same sql query as with queryover, with the same problem as result.
我知道这在 hql 中是可能的,但我如何使用 ICriteria 的 QueryOver 来做到这一点?
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).
推荐答案
如果 Linq 是一个选项,请使用
if Linq is an option use
session.Query<EntityWithDictionary>()
.Where(f => f.Dictionary["key"] == "value")
.ToList();
这篇关于NHibernate QueryOver 字典(地图)的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!