流利的Hibernate复制记录而不是更新

时间:2016-06-27 08:41:28

标签: fluent-nhibernate

//下面我们有从BO对象继承的域对象,它有save和// update方法。 //
//在我们的UI中,我们希望能够在用户单击//保存按钮时执行以下操作。 //
//插入新对象时,此方法可正常工作。更新从数据库读取的//现有对象时,对象将被复制而不是//更新。 //
//不确定为什么SaveOrUpdate和Merge Nhibernate方法会破坏新的//对象而不是更新记录? //
//保存方法是否无法告诉对象有密钥因此//更新而不是复制记录?

        private void BtnSave_Click(object sender, EventArgs e)
        {

            if (person.PersonID > 0)
            {
                person.Update();
            }
            person.Save();


        }



public class BO<T>
        {
            private ISessionFactory _sessionFactory;
            private ISession _session;

            public BO()
            {
               // CreateSession();
            }
            private void CreateSession()
            {
                string connectionString = "Data Source=(local)\\SQLExpress;Initial Catalog=c;Integrated Security=True;Pooling=true";
                /*
                 Hibernate start session to read and write to MSSQL database
                */
                if (_session != null && _session.IsOpen)
                {
                    _session.Flush();
                    _session.Close();
                }
                if (_sessionFactory != null && !_sessionFactory.IsClosed)
                {
                    _sessionFactory.Close();
                }
    //Create a new session from the session factory
                _sessionFactory = CWISessionFactory.CreateFactory<Person>(connectionString);
                _session = _sessionFactory.OpenSession();

            }
            public virtual void Update()
            {
                CreateSession();

                using (ITransaction tran = _session.BeginTransaction())
                {
                    bool isd = _session.IsDirty();
                     _session.SaveOrUpdate(this);

                    _session.Flush();
                    tran.Commit();

                    _session.Close();
                    _sessionFactory.Close();
                }
            }
            public virtual void Save()
            {
                CreateSession();
                {
                    using (ITransaction tran = _session.BeginTransaction())
                    {
                        bool isd = _session.IsDirty();
                       _session.Save(this);
                        CloseSession(tran);
                    }
                }

            }

            private void CloseSession(ITransaction tran)
            {
                _session.Flush();
                tran.Commit();
                _session.Close();
                _sessionFactory.Close();
            }
            private void CloseSession()
            {
                _session.Flush();
                _session.Close();
                _sessionFactory.Close();
            }
            public virtual ISession GetSession()
            {
                CreateSession();
                return _session;
            }
//Object collections can be retrieved from calling the method below.
            public virtual ICollection<T> Collection()
            {
                IList<T> ilist = new List<T>();

                CreateSession();
                if (typeof(T) == typeof(Country))
                {
                    ilist = _session.QueryOver<Country>().List<T>();
                }
                if (typeof(T) == typeof(Title))
                {
                    ilist = _session.QueryOver<Title>().List<T>();
                }
                else if (typeof(T) == typeof(Role))
                {
                    ilist = _session.QueryOver<Role>().List<T>();
                }
                else if (typeof(T) == typeof(Status))
                {
                    ilist = _session.QueryOver<Status>().List<T>();

                }
                else if (typeof(T) == typeof(Gender))
                {
                    ilist = _session.QueryOver<Gender>().List<T>();

                }
                CloseSession();
                return ilist;

            }
 //Can search for an object using the method below
            public virtual object GetObjectByKey(int key)
            {
                CreateSession();
                object o = _session.Get<T>(key);
                CloseSession();
                return o;


            }

        }

    //Business object currently not updating

     public class Person : BO<Person>
        {
            public Person()
            {
                Title = new Title();
                Gender = new Gender();
                Role = new Role();
                Status = new Status();
                //this.Address = new Address();
            }
            public virtual int PersonID
            {
                get;
                protected set;
            }
            public virtual string FirstName
            { get; set; }
            public virtual string SecondName
            { get; set; }
            public virtual string IDNumber
            { get; set; }
            public virtual string Initials
            { get; set; }
            public virtual string Surname
            { get; set; }
            public virtual DateTime ? DateOfBirth
            { get; set; }
            public virtual string HomeTelephone
            { get; set; }
            public virtual string WorkTelephone
            { get; set;
            }
            public virtual int TitleID
            { get; set; }
            public virtual string Email 
            { get; set; }
            public virtual string CellurPhoneNumber
            { get; set; }
            public virtual string Password
            { get; set; }
            public virtual int ? OccupationID
            { get; set; }
            public virtual bool AcceptedMandate
            { get; set; }
            public virtual int ? GenderID
            { get; set; }
            public virtual string InvestmentAccountNumber
            { get; set; }
            public virtual int ? StatusID
            {
                get;
                set;
            }
            public virtual int? RoleID
            {
                get;
                set;
            }
            public virtual int? AddressID
            {
                get;
                set;
            }
            public virtual Title Title
            {
                get;
                set;
            }
            public virtual Role Role
            {
                get;
                set;
            }
            public virtual Status Status
            {
                get;
                set;
            }
            public virtual Gender Gender
            {
                get;
                set;
            }

            public virtual Int32 CountryOfPassportID
            {
                get;set;
            }
            public virtual DateTime? PassportExpiryDate
            {
                get; set;
            }
            public virtual string PassportNumber
            {
                get; set;
            }
            public virtual Country CountryOfPassport
            {
                get;set;
            }
            public virtual Address Address
            {
                get; set;
            }
            public override string ToString()
            {
                return Surname+" "+FirstName+" "+SecondName;
            }
            public virtual IList<Person> Search(string firstname, string surname)
            {
                var session = GetSession();

                return session.CreateCriteria<Person>()
                .Add(Expression.Sql("lower(FirstName) like lower(?)", "%"+firstname.ToLower()+"%", NHibernateUtil.String))
                .Add(Expression.Sql("lower(Surname) like lower(?)", "%" + surname.ToLower()+ "%" , NHibernateUtil.String))
                .Add(Expression.Sql("RoleID = ?", 1, NHibernateUtil.Int32))
                //.Add(Expression.Eq("RoleID", 1))
                .List<Person>();

            }

            public virtual IList<Person> SearchNew(string passportnumber, string surname )
            {
                var session = GetSession();

                return session.CreateCriteria<Person>()            .List<Person>();

            }


        }

//Fluent mapping for Person object

    public class PersonMap : ClassMap<Person>
        {
            public PersonMap()
            {

                Id(x => x.PersonID).GeneratedBy.Increment().UnsavedValue(0);
                Map(x => x.AcceptedMandate);
                Map(x => x.CellurPhoneNumber );
                Map(x => x.DateOfBirth);
                Map(x => x.Email);
                Map(x => x.FirstName);
                //Map(x => x.GenderID);
                Map(x => x.HomeTelephone);
                Map(x => x.Initials);
                Map(x => x.InvestmentAccountNumber);
                Map(x => x.OccupationID);
                Map(x => x.Password);
                Map(x => x.SecondName);
                Map(x => x.IDNumber);
                Map(x => x.PassportExpiryDate);
                Map(x => x.PassportNumber);
                // Map(x => x.RoleID);
                Map(x => x.Surname);
               // Map(x => x.TitleID);
                Map(x => x.WorkTelephone);
                References(x => x.Role).Column("RoleID").Update().Insert().Cascade.None();
                References(x => x.Title).Column("TitleID").Update().Insert().Cascade.None();
                References(x => x.Status).Column("StatusID").Update().Insert().Cascade.None();
                References(x => x.Gender).Column("GenderID").Update().Insert().Cascade.None();
                References(x => x.CountryOfPassport).Column("CountryOfPassportID").Update().Insert().Cascade.None();
                References(x => x.Address).Column("AddressID").Update().Insert().Cascade.None();

            }

        }
   //Related object mapped to Person

//Business oject definition for Gender object related to person 
        public class Gender:BO<Gender>
        {

            public virtual int GenderID { get; protected set; }
            public virtual string Name { get; set; }
            public override string ToString()
            {
                return Name;
            }

        }
        class GenderMap : ClassMap<Gender>
        {
            public GenderMap()
            {

                Id(x => x.GenderID).GeneratedBy.Increment().UnsavedValue(0);
                Map(x => x.Name);

            }

        }

1 个答案:

答案 0 :(得分:0)

            if (person.PersonID > 0)
            {
                person.Update();
            }
            else
            {
                 person.Save();
            }

// BO类上缺少的else语句解决了问题:)。 //不是正确的方法,因为给定了一个Windows UI控件构造函数//接收一个Person,如下所示 //在绑定到UI之前需要重新检索对象,否则更新//插入重复记录。

    public ctrlClient(Person person)
    {
        InitializeComponent();
        this.person =(Person) person.GetObjectByKey(person.PersonID);

        Create();
    }