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 3288490
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T20:36:48+00:00 2026-05-17T20:36:48+00:00

I am using NHibernate and this is not a Homework. Suppose I have retrieved

  • 0

I am using NHibernate and this is not a Homework.

Suppose I have retrieved an object of type Faculty(suppose Faculty of Engineering in the University of XYZ) from the database. It has 5 child objects associated with it of type Department and should contain IDs 2,4,5,8 and 9 according to the database-table.

My 1st problem is, I see that the associated objects always have ID set as 0.

Faculty-ID is loading correctly.

My 2nd problem is, I need to load them into a combo box and want the object selected whose ID is 5.

How can I solve the problem of ID set to 0? I don’t know why it is happening.

How to select the object of ID==5?

Faculty.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping
    xmlns="urn:nhibernate-mapping-2.2"
    namespace="UserManagememntApplication.BO"
    assembly="UserManagememntApplication.BO" >

  <class name="Faculty" table="b_Faculty">
    <id column="ID" name="ID" type="System.Int32" >
      <generator class="native" />
    </id>

    <property column="Code" name="Code" />
    <property column="Name" name="Name" />
    <property column="IsActive" name="IsActive" />

    <bag name="DepartmentItems" table="b_Department">
      <key column="FacultyID"/>
      <one-to-many class="Department" />
    </bag>
  </class>
</hibernate-mapping>

Department.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping
    xmlns="urn:nhibernate-mapping-2.2"
    namespace="UserManagememntApplication.BO"
    assembly="UserManagememntApplication.BO" >

  <class name="Department" table="b_Department">
    <id column="ID" name="ID" type="System.Int32" >
      <generator class="native" />
    </id>

    <property column="Code" name="Code" />
    <property column="Name" name="Name" />
    <property column="IsActive" name="IsActive" />

    <many-to-one name="Faculty" class="Faculty" column="FacultyID" unique="true"  />

    <bag name="TeacherItems" table="b_Teacher">
      <key column="DepartmentID"/>
      <one-to-many class="Teacher" />
    </bag>
  </class>
</hibernate-mapping>

b_Faculty

CREATE TABLE [dbo].[b_Faculty](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Code] [varchar](50) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [IsActive] [bit] NOT NULL,
 CONSTRAINT [PK_b_Faculty] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

b_Department

CREATE TABLE [dbo].[b_Department](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [FacultyID] [int] NOT NULL,
    [Code] [varchar](50) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [IsActive] [bit] NOT NULL,
 CONSTRAINT [PK_b_Department] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Edit:

Faculty.cs

public class Faculty : BusinessObject<Faculty>
    {
        public virtual string Code { get; set; }
        public virtual string Name { get; set; }
        public virtual bool IsActive { get; set; }

        public virtual IEnumerable<Department> DepartmentItems { get; set; }
    }

Department.cs

public class Department : BusinessObject<Department>
    {
        public virtual string Code { get; set; }
        public virtual string Name { get; set; }
        public virtual bool IsActive { get; set; }

        public virtual Faculty Faculty { get; set; }

        public virtual IEnumerable<Teacher> TeacherItems { get; set; }
    }

BusinessObject.cs

public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T>
    {
        public int ID { get; set; }

        public static bool operator ==(BusinessObject<T> item1, BusinessObject<T> item2)
        {
            bool same = false;

            if (!object.ReferenceEquals(item1, null) && !object.ReferenceEquals(item2, null))
            {
                if (item1.ID == item2.ID)
                {
                    same = true;
                }
            }

            else
            {
                if (object.ReferenceEquals(item1, null) && object.ReferenceEquals(item2, null))
                {
                    same = true;
                }
            }

            return same;
        }

        public static bool operator !=(BusinessObject<T> item1, BusinessObject<T> item2)
        {
            return !(item1 == item2);
        }

        public override bool Equals(object obj)
        {
            //If "obj" is null, they are obviously not equal.
            if (obj == null)
            {
                return false;
            }

            //If the objects are the same instance, they must be equal.
            if (Object.ReferenceEquals(this, obj))
            {
                return true;
            }

            //If the objects are not the same type, they cannot be equal.
            if (this.GetType() != obj.GetType())
            {
                return false;
            }

            T objCustomer = (T)obj;

            if (this.ID > 0 && objCustomer.ID > 0)
            {
                if (this.ID.Equals(objCustomer.ID))
                {
                    return true;
                }

            }
            return false;
        }

        public override int GetHashCode()
        {
            if (this.ID <= 0)
            {
                return base.GetHashCode();
            }
            else
            {
                return ID.GetHashCode();
            }
        }
    }

FacultyRepository.cs

public class FacultyRepository : Repository<Faculty>
    {
    }

DepartmentRepository.cs

public class DepartmentRepository : Repository<Department>
    {
    }

Repository.cs

public class Repository<T> : IRepository<T>
    {
        ISession _session;

        public Repository() 
        {
            _session = SessionFactory.GetOpenSession();
        }

        public T Get(object id)
        {
            T obj = default(T);

            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();
                    obj = (T)_session.Get<T>(id);
                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }

            return obj;
        }

        public IEnumerable<T> Get(string fieldName, object fieldValue)
        {
            IEnumerable<T> list = null;

            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();
                    list = (IEnumerable<T>)_session.CreateCriteria(typeof(T))
                        .Add(new NHibernate.Expression.EqExpression(fieldName, fieldValue))
                        .List<T>();

                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }

            return list;
        }

        public IEnumerable<T> Get()
        {
            IEnumerable<T> list = null;

            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();
                    list = (IEnumerable<T>)_session.CreateCriteria(typeof(T)).List<T>();
                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }

            return list;
        }

        public void SaveOrUpdate(T obj)
        {
            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();
                    _session.SaveOrUpdateCopy(obj);
                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }
        }

        public void SaveOrUpdate(IEnumerable<T> objs)
        {
            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();

                    foreach (T obj in objs)
                    {
                        _session.SaveOrUpdate(obj);
                    }

                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }
        }

        public void Delete(T obj)
        {
            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();
                    _session.Delete(obj);
                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();                
                _session.Clear();

                throw ex;
            }
        }

        public void Delete(IEnumerable<T> objs)
        {
            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();

                    foreach (T obj in objs)
                    {
                        _session.Delete(obj);
                    }

                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();
                _session.Clear();

                throw ex;
            }
        }

        public void DeleteAll()
        {
            try
            {
                if (!_session.Transaction.IsActive)
                {
                    _session.BeginTransaction();

                    DetachedCriteria criterion = DetachedCriteria.For<T>();
                    IList<T> list = criterion.GetExecutableCriteria(_session).List<T>();

                    foreach (T item in list)
                    {
                        _session.Delete(item);
                    }

                    _session.Transaction.Commit();
                    _session.Flush();
                }
                else
                {
                    throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
                }
            }
            catch (Exception ex)
            {
                _session.Transaction.Rollback();

                throw ex;
            }
        }

        public void Dispose()
        {
            if (_session != null)
            {
                _session.Clear();
                _session.Close();
                _session = null;
            }
        }
    }

SessionFactory.cs

public class SessionFactory
    {
        private static ISessionFactory _sessionFactory = null;
        private SessionFactory(){}

        static SessionFactory()
        {
            if (_sessionFactory == null)
            {
                Configuration configuration = new Configuration();
                configuration.Configure();
                _sessionFactory = configuration.BuildSessionFactory();
            }
        }

        public static ISession GetOpenSession()
        {
            return _sessionFactory.OpenSession();
        }
    }

This is all I have.

  • 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-05-17T20:36:49+00:00Added an answer on May 17, 2026 at 8:36 pm

    An extremely wild guess. Could you try to run your code without the equality comparers and the Equals implementation and see whether that helps, so with the following implementation:

    public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T>
    {
        public int ID { get; set; }
    }
    

    Another thing you may want to try is to set the ID to private:

    public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T>
    {
        public int ID { get; private set; }
    }
    

    See what the effect of that is.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Looking to do a bit of refactoring... Using NHibernate I have this query currently
I am using nhibernate and i have code like this in the mapping area:
I'm using FluentNHibernate but NHibernate XML will do. Say I have this model public
I have a Data Service created using WCF that internally uses nHibernate. This WCF
I started using NHibernate this week (struggling). I have a small application with 3
In a project using NHibernate, I have this class : public class AdminVAT :
I am using nhibernate 3 and fluent nhibernate I have this enum [Flags] public
I need to get this query using NHibernate: Select RequestStatus.[Status], Count(ApprovalRequest.Id) From ApprovalRequest Inner
I've been using NHibernate for a while now and have found from time to
I have a problem with NHibernate not using my mappings configuration for eager loading

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.