Nhibernate 查询具有包含值的字典属性的项目

标签 nhibernate fluent-nhibernate linq-to-nhibernate nhibernate-criteria

我需要一种在 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/

相关文章:

oop - NHibernate 无法解析继承属性的属性

nhibernate - 如何在 (n)hibernate 中对子对象的属性进行排序?

c# - 如何使用 nhibernate SchemaUpdate 功能更改列

nhibernate - 在NHibernate(Fluent)中,如何将引用对象的属性映射到父对象?

c# - 如何将 Nullable<T> 参数与 nHibernate Linq 表达式一起使用?

c# - 在不使用 Where() 的情况下使用 GroupBy() 和 Timeout() 时出现 NotSupportedException

c# - 帮助使 Fluent NHibernate 为每个表创建一个 oracle 序列

nhibernate - Fluent nHIbernated - 在同一张表中有许多关系

repository - 如何将 Linq2NHibernate 的 .Fetch 和 .ThenFetch 包装到我的抽象存储库中?

sql-server - 如何调试缓慢的 NHibernate Select 查询?