Nhibernate query for items that have a Dictionary Property containing value

前端 未结 1 767
终归单人心
终归单人心 2020-12-18 05:42

I need a way to query in Nhibernate for items that have a Dictionary Property containing value.

Assume:

public class Item
{
     public virtual IDict         


        
相关标签:
1条回答
  • 2020-12-18 06:35

    Handling IDictionary<TValueType, TValueType> would usually bring more issues than advantages. One way, workaround, is to introduce a new object (I will call it MyWrapper) with properties Key and Value (just an example naming).

    This way we have to 1) create new object (MyWrapper), 2) adjust the mapping and that's it. No other changes... so the original stuff (mapping, properties) will work, because we would use different (readonly) property for querying

    public class MyWrapper
    {
        public virtual int Key { get; set; }
        public virtual string Value { get; set; }
    }
    

    The Item now has

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

    Now we will extend the mapping:

    HasMany(x => x.Properties)
        .Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
        .Component(c =>
        {
            c.Map(x => x.Key).Column("IDNumber")
            c.Map(x => x.Value).Column("TextField")
        })
        ...
        ;
    

    And the Query, which will work as expected:

    session
        .Query<Item>()
        .Where(r => 
            r.Properties.Any(g => g.Value == "SomeText")
        )
    

    NOTE: From my experience, this workaround should not be workaround. It is preferred way. NHibernate supports lot of features, but working with Objects brings more profit

    0 讨论(0)
提交回复
热议问题