NHibernate对象id返回不正确的值

时间:2010-10-23 01:40:42

标签: c# combobox c#-2.0

我正在使用NHibernate,这不是一个家庭作业。

假设我从数据库中检索了Faculty类型的对象(假设XYZ大学的工程学院)。它有5个与Department类型相关联的子对象,根据数据库表应包含ID 2,4,5,8和9。

我的第一个问题是,我发现关联的对象始终将ID设置为0

Faculty-ID正确加载。

我的第二个问题是,我需要将它们加载到一个组合框中,并希望选择ID为5的对象。

如何解决ID设置为0的问题?我不知道为什么会这样。

如何选择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]

编辑:

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();
        }
    }

这就是我的全部。

3 个答案:

答案 0 :(得分:2)

非常疯狂的猜测。您是否可以尝试在没有相等比较器和Equals实现的情况下运行代码,看看是否有帮助,所以使用以下实现:

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

您可能想要尝试的另一件事是将ID设置为私有:

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

看看它的效果是什么。

答案 1 :(得分:0)

关于ComboBox问题,我会执行以下操作:

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();

答案 2 :(得分:0)

我有一个类似的问题,在执行select之后id返回为0。 我正在使用Fluent Nhibernate并且在持久化类和子类中声明了id字段。 只需从子类中删除id。