我需要一种在 Nhibernate 中查询具有包含值的字典属性的项目的方法。
认为:
public class Item
{
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
}
和映射:
public ItemMap()
{
HasMany(x => x.DictionaryProperty)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.AsMap<string>(
index => index.Column("IDNumber").Type<int>(),
element => element.Column("TextField").Type<string>().Length(666)
)
.Cascade.AllDeleteOrphan()
.Fetch.Join();
}
我要查询所有
Item
具有“SomeText”字典值的 s。 Linq 中的以下示例失败:session.Query<Item>().Where(r => r.DictionaryProperty.Any(g => g.Value == "SomeText"))
有错误
cannot dereference scalar collection element: Value
那么有没有办法在 NHibernate 中实现这一目标? Linq 不是唯一的要求,而是它的首选。并不是说我没有兴趣查询字典 key 可以使用
.ContainsKey
实现. Φορ this相似但不相同
最佳答案
搬运 IDictionary<TValueType, TValueType>
通常会带来更多的问题而不是优势。一种方式,解决方法 , 是引入一个具有属性 Key
的新对象(我将称其为 MyWrapper)和 Value
(只是一个示例命名)。
这样我们必须 1) 创建新对象 (MyWrapper),2) 调整映射,仅此而已。没有其他变化......所以原始的东西(映射,属性)将起作用,因为我们将使用不同的(只读)属性进行查询
public class MyWrapper
{
public virtual int Key { get; set; }
public virtual string Value { get; set; }
}
该项目现在有
public class Item
{
// keep the existing for Insert/Updae
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
// map it
private IList<MyWrapper> _properties = new List<MyWrapper>();
// publish it as readonly
public virtual IEnumerable<MyWrapper> Properties
{
get { return new ReadOnlyCollection<MyWrapper>(_properties); }
}
}
现在我们将扩展映射:
HasMany(x => x.Properties)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Component(c =>
{
c.Map(x => x.Key).Column("IDNumber")
c.Map(x => x.Value).Column("TextField")
})
...
;
和查询,它将按预期工作:
session
.Query<Item>()
.Where(r =>
r.Properties.Any(g => g.Value == "SomeText")
)
注意:根据我的经验,这个 解决方法 不应该是解决方法。这是首选方式。 NHibernate 支持很多特性,但使用 Objects 会带来更多 yield
关于Nhibernate 查询具有包含值的字典属性的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829531/