views:

59

answers:

2

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.

+2  A: 

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.

Pieter
@Pieter, I have solved my problem. In 'BusinessObject.cs', I forgot to add the modifier virtual to the property ID. As soon as I added the keyword virtual, it is working fine. Since NHibernate was not giving any warning, I was overlooking it all the way.
JMSA
That's very strange because NHibernate throws when you load an object with a non-virtual property. Glad you found it though. If I change my answer, do I get the bounty? Just kidding :P.
Pieter
Now, to get 50 bounty-points, can you please solve my ComboBox-related problem?
JMSA
ROFL............
Pieter
A: 

Concerning the ComboBox issue, I would do the following:

var faculty = GetFaculty();
int selectedID = 5;

int selectedIndex = -1;

comboBox1.BeginUpdate();

comboBox1.Items.Clear();

foreach (var department in faculty.DepartmentItems)
{
    int index = comboBox1.Items.Add(department);

    if (department.ID == selectedID)
        selectedIndex = index;
}

if (selectedIndex != -1)
    comboBox1.SelectedIndex = selectedIndex;

comboBox1.EndUpdate();
Pieter
Maybe I don't understand the question, but the above approach is the one I would take. If this is not what you're looking for, could you please expand the question?
Pieter
This is not working! I am trying it myself. But points to you anyway.
JMSA
Yes, this happens sometimes. I've updated the answer to work with the `SelectedIndex` instead. Btw, I don't think you've awarded the bounty yet. I believe you have to do that manually.
Pieter
See this: http://stackoverflow.com/questions/4027137/how-to-solve-this-combobox-item-setting-problem
JMSA
I think this has to do with your equality implementation. Gave a try at your other question :).
Pieter