Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8382883
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T17:01:50+00:00 2026-06-09T17:01:50+00:00

I have a complex situation, where I need to map three different classes with

  • 0

I have a complex situation, where I need to map three different classes with NHibernate. Class1(Branch.cs) has a collection of Class2(Employee.cs) objects. At the same time Class2 also has a collection of Class3(Contacts.cs) objects.
As data is very huge I used fetch keyword to retrieve data in single query.

I used the query as

Query1 – “from Branch b inner join fetch b.Employee e inner join fetch e.Contacts” – Single query but duplicate results.

Query2 – “from Branch b inner join fetch b.Employee” – Multiple query, required results.

I have used bags in mapping files. The query result seems to having duplicate results.
How to remove duplicate results as well as retrieving data in single query.
I am including mapping files as well as Classes.

Contacts.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateSample" namespace="NHibernateSample">
  <class name="Contacts" table="Contacts">
      <id name="EmployeeID"/>
      <property name="EmployeeID"/>
      <property name="Mobile"/>
      <property name="Alternate"/>
  </class>
</hibernate-mapping>

Branch.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateSample" namespace="NHibernateSample">
  <class name="Branch" table="Branch">
      <id name="BranchCode"/>
      <property name="BranchCode"/>
      <property name="BranchName"/>
      <bag name="EmployeeList" cascade="all-delete-orphan" inverse="false" batch-size="10000">
          <key column="BranchCode"/>
          <one-to-many class="Employee" />
      </bag>
  </class>

</hibernate-mapping>

Employee.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateSample" namespace="NHibernateSample">
  <class name="Employee" table="Employee">
      <id name="EmployeeId"/>
      <property name="EmployeeId"/>
      <property name="FirstName"/>
      <property name="LastName"/>
      <property name="BranchCode"/>
      <bag name="Contact" cascade="all-delete-orphan" inverse="false" batch-size="10000">
          <key column="EmployeeID"/>
          <one-to-many class="Contacts" />
      </bag>
  </class>
</hibernate-mapping>

Contacts.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace NHibernateSample
{
    public class Contacts
    {
        String employeeID;
        String mobile;
        String alternate;

        public Contacts()
        { }


        public virtual String EmployeeID
        {
            get { return employeeID; }
            set { employeeID = value; }
        }

        public virtual String Mobile
        {
            get { return mobile; }
            set { mobile = value; }
        }        
        public virtual String Alternate
        {
            get { return alternate; }
            set { alternate = value; }
        }
    }
}

Employee.cs

    using System;
using System.Collections.Generic;
using System.Text;

namespace NHibernateSample
{
    public class Employee
    {
        String employeeId;
        String firstName;
        String lastName;
        String branchCode;
        List<Contacts> contact = new List<Contacts>();

        public virtual List<Contacts> Contact
        {
            get { return contact; }
            set { contact = value; }
        }
        public virtual String EmployeeId
        {
            get { return employeeId; }
            set { employeeId = value; }
        }

        public virtual String FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }

        public virtual String LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }

        public virtual String BranchCode
        {
            get { return branchCode; }
            set { branchCode = value; }
        }

        public Employee()
        { }
    }
}

Branch.cs

    using System.Collections.Generic; 
using System.Text; 
using System; 


namespace NHibernateSample 
{
    [Serializable]
    public class Branch
    {
        private String branchCode;
        private String branchName;
        private IList<Employee> employeeList = new List<Employee>();

        public virtual IList<Employee> EmployeeList
        {
            get { return employeeList; }
            set { employeeList = value; }
        }
        public virtual String BranchCode
        {
            get { return branchCode; }
            set { branchCode = value; }
        }

        public virtual String BranchName
        {
            get { return branchName; }
            set { branchName = value; }
        }

        public Branch() { }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T17:01:51+00:00Added an answer on June 9, 2026 at 5:01 pm

    This is an issue with NHibernate which they won’t fix.

    You can get the result correct on the first level by applying the DistinctEntityTransformer, this is a built in transformer in the NHibernate and u should apply it to the queryover object using

    QueryOver.TranformUsing(Tranformers.DistinctEntityTransformer).
    

    On multilevel such as your problem you will need to write your own transformer and use it instead of the distinct entity transformer. you can use similar logic to the distinct entity transformer provided by NHibernate to fix the replications at the details.

    Edit: Here is an implementation of this:

    public class MultiLevelDistinctEntityTransformer : IResultTransformer
    {
        private readonly Dictionary<Type, List<String>> _fetchedCollectionProperties; // used to know which properties are fetched so you don't fetch more details than required
    
        public MultiLevelDistinctEntityTransformer(Dictionary<Type, List<String>> fetchedCollectionProperties)
        {
            _fetchedCollectionProperties = fetchedCollectionProperties;
        }
    
        public object TransformTuple(object[] tuple, string[] aliases)
        {
            return tuple.Last();
        }
    
        public IList TransformList(IList list)
        {
            if (list.Count == 0)
                return list;
            var result = (IList) Activator.CreateInstance(list.GetType());
            var distinctSet = new HashSet<Entity>();
            foreach (object item in list)
            {
                var entity = item as Entity; // Entity is the base class of my nhibernate classes
                if (entity == null)
                    continue;
                if (distinctSet.Add(entity))
                {
                    result.Add(item);
                    HandleItemDetails(item);
                }
            }
            return result;
        }
    
        private void HandleItemDetails(object item)
        {
            IEnumerable<PropertyInfo> collectionProperties =
                item.GetType().GetProperties().Where(
                    prop =>
                    prop.IsCollectionProperty()/*extension method which checks if the object inherits from ICollection*/ &&
                    _fetchedCollectionProperties.ContainsKey(item.GetType()) &&// get only the fetched details
    
                    _fetchedCollectionProperties[item.GetType()].Contains(prop.Name));
            foreach (PropertyInfo collectionProperty in collectionProperties)
            {
                dynamic detailList = collectionProperty.GetValue(item, null);
                if (detailList != null)
                {
                    dynamic uniqueValues =
                        Activator.CreateInstance(
                            typeof (List<>).MakeGenericType(collectionProperty.PropertyType.GetGenericArguments()[0]));
                    var distinct = new HashSet<Entity>();
                    foreach (var subItem in detailList)
                    {
                        var entity = subItem as Entity;
                        if (distinct.Add(entity))
                        {
                            uniqueValues.Add(subItem);
                            HandleItemDetails(subItem);
                        }
                    }
                    collectionProperty.SetValue(item, uniqueValues, null);
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to solve a complex situation, where i already have a Canvas element
I need to know how to handle a pretty complex situation. I have a
I have several complex data structures like Map< A, Set< B > > Set<
I have some complex regular expressions which I need to comment for readability and
We have a product that we need to create an installer for. It has
I have a situation where in a web application a user may need a
I have a situation where I am attempting to port some big, complex python
So I got this situation and I may have 2 different routes to take.
Here is the situation. I have some ViewModels that contain nested complex model types.
I have a situation where I need select the current and previous order amount

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.