How to get a distinct result with nHibernate and QueryOver API?

前端 未结 4 2087
悲&欢浪女
悲&欢浪女 2020-12-25 10:01

I have this Repository method

    public IList ListMessagesBy(string text, IList tags, int pageIndex, out int count, out int pageSi         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 10:37

    I have recently created a method to apply select distinct based on a mapped object type. It applies this to an IQueryOver object (property of class). Method also has access to the nhibernate config. You could add these as method parameters. Needs work for production, but method is working great in dev, only used it for one entity so far.

    This method was created because I am trying to page my data at the server level and a distinct result transformer would not work.

    After you get your object collection (query.List()) you may have to reload the objects to populate one to many child objects. Many to one mappings will be proxied for lazy loads.

     public void DistinctRootProjectionList()
        {
            var classMapping = Context.Config.GetClassMapping(typeof(E));
            var propertyIterator = classMapping.UnjoinedPropertyIterator;
            List projections = new List();
            ProjectionList list = Projections.ProjectionList();
    
            list.Add(Projections.Property(classMapping.IdentifierProperty.Name), classMapping.IdentifierProperty.Name);
    
            foreach (var item in propertyIterator)
            {
                if (item.Value.IsSimpleValue || item.Value.Type.IsEntityType)
                {
                    list.Add(Projections.Property(item.Name), item.Name);
                }
            }
            query.UnderlyingCriteria.SetProjection(Projections.Distinct(list));
            query.TransformUsing(Transformers.AliasToBean());
        }
    

    Code I used to load one to many relations... T is the entity type.

    for (int i = 0; i < resp.Data.Count; i++)
            {
                resp.Data[i] = session.Load(GetInstanceIdValue(resp.Data[i]));
            }
    

提交回复
热议问题