NHibernate filter collection

前端 未结 2 1109
予麋鹿
予麋鹿 2021-01-13 06:48

Using NHibernate I want to filter a collection in a class to contain ONLY a subset of possible objects. Below I am including a sample table data to help explain. I can fin

2条回答
  •  抹茶落季
    2021-01-13 07:20

    if you want to filter the collection on demand, using a filter is a valid choice. You would need to declare the filter on both the Version class and in the bag element and apply the filter from the NHibernateSession.EnableFilter method

    if you always want to fetch a single Version in the bag then implement a 'where' in the mapping of the bag:

    
        
        
    
    

    note that in the 'where' you write proper SQL not HQL and as such the proper SQL i write above probably has to be changed to reflect your schema

    Additionally if a single object is to be fetched setting up a bag and the according IList may be an overkill. Applying a formula property and a DataObjectVersion object in the class may be more appropriate

    in the class DataObject replace the IList with

    public virtual DataObjectVersion Version { get; set; }
    

    and in the mapping replace the 'bag' with something in the lines of

    
    

    again only proper SQL is allowed

    i've used computed properties with native datatypes (datetime, string etc) and fetching an Entity may (or may not) need something more or different

    Last but not least, you could apply a filter on the collection after you have fetched the primary object DataObject by creating a filter on the collection

    IList  fVersion = 
        NHibernateSession.CreateFilter(do.Versions, "where VersionNumber = :ver")
            .SetParameter("ver", do.CurrentVersionNumber)
            .List();
    

    where the do.Versions collection is not initialized, only the results fetched in the separate fVersion collection and this is a second SELECT after already having made the round-trip to the db for the DataObject fetch.

提交回复
热议问题