Solved

Persisting data using NHibernate 3.0 in ASP.NET/C#

Posted on 2012-03-16
6
307 Views
Last Modified: 2012-03-21
Hello Experts!

I apologize for this being long-winded, I just want to be sure you have all the necessary information to assist! Thanks in advance!

So I am trying to implement an ORM into my ASP.NET application. I chose NHibernate, and played around with a few tutorials, but I am still very new to it. I am having trouble persisting data back to the database, and I believe the problem is in my hbm.xml mapping files.

Here is my database schema, very simple...

Database schema
And here are my Model classes
    using System;
    using Microdesk.Domain.Foundation;

    public class Employee : GuidIdentityPersistenceBase<Employee>
    {
        public virtual Guid Id
        { 
            get { return _persistenceId; }
        }
        
        public virtual string Firstname { get; set; }
        public virtual string Lastname { get; set; }
        public virtual string Email1 { get; set; }
        public virtual string Email2 { get; set; }
        public virtual string Extension { get; set; }
        public virtual string Mobile { get; set; }
        public virtual bool Manager { get; set; }
        public virtual Department Department { get; set; }

        public virtual string Fullname
        {
            get { return Firstname + " " + Lastname; }
        }

        public virtual string FormattedMobile()
        {
            return "(" + Mobile.Substring(0, 3) + ")" + " " + Mobile.Substring(3, 3) + "-" + Mobile.Substring(6);
        }
    }


    using System;
    using Microdesk.Domain.Foundation;

    public class Department : GuidIdentityPersistenceBase<Department>
    {
        public virtual Guid Id
        {
            get { return _persistenceId; }
        }

        public virtual string Name { get; set; }
    }

Open in new window


And my hbm.xml files..
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="EmployeePhoneBook.DomainModel"
                   namespace="EmployeePhoneBook.DomainModel"
                   default-access="field.camelcase-underscore"
                   default-lazy="true">

  <class name="Employee" table="Employee" >
    <id name="_persistenceId" column="Id" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000" >
      <generator class="guid.comb" />
    </id>
    <version name="_persistenceVersion" column="Version" access="field" type="int" unsaved-value="0"/>
    <property name="Firstname" length="50" not-null="true"/>
    <property name="Lastname" length="50" not-null="true"/>
    <property name="Email1" length="100" />
    <property name="Email2" length="100" />
    <property name="Extension" length="4" />
    <property name="Mobile" length="10" />
    <property name="Manager" not-null="true"/>
    <many-to-one name="Department" class="EmployeePhoneBook.DomainModel.Department" cascade="save-update" not-null="true" >
      <column name="DepartmentId" />
    </many-to-one>
  </class>
</hibernate-mapping>

Open in new window


<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="EmployeePhoneBook.DomainModel"
                   namespace="EmployeePhoneBook.DomainModel"
                   default-access="field.camelcase-underscore"
                   default-lazy="true">

  <class name="Department" table="Department" >
    <id name="_persistenceId" column="Id" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000" >
      <generator class="guid.comb" />
    </id>
    <property name="Name" column="Name" length="100" not-null="true"/>
  </class>
</hibernate-mapping>

Open in new window


I am attempting to use the SaveOrUpdate(T entity) in my repository. If the record is new it saves the record in both tables, whereas I only want it to save to the employee table but use the department selected from a dropdown. Instead it saves a new record to both tables. Also, It does not perform updates as it should. It saves a new record to both tables..

Repository
    public interface IEmployeeRepository
    {
        Employee SaveOrUpdateEmployee(Employee emp);
        Employee GetEmployee(Guid Id);
        void DeleteEmployee(Employee emp);
        IList<Employee> GetAllEmployees(); 
    }

    public class EmployeeRepository : Rhino.Commons.NHRepository<Employee>, IEmployeeRepository
    {
        #region Implementation of IEmployeeRepository

        public Employee SaveOrUpdateEmployee(Employee emp)
        {
            return base.SaveOrUpdate(emp);
        }

        public Employee GetEmployee(Guid Id)
        {
            return base.Get(Id);
        }

        public void DeleteEmployee(Employee emp)
        {
            base.Delete(emp);
        }

        public IList<Employee> GetAllEmployees()
        {
            return base.FindAll().ToList<Employee>();
        }

        #endregion
    }

Open in new window




And finally calling code...
        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult EditEmployee(Guid editId)
        {
            Employee employeeToEdit;
            using (UnitOfWork.Start())
            {
                employeeToEdit = _employeeRepository.GetEmployee(editId);
            }

            return View("EditEmployee", employeeToEdit);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditEmployee(Employee employee)
        {
            if (ModelState.IsValid)
            {
                using (UnitOfWork.Start())
                {
                    employee = _employeeRepository.SaveOrUpdateEmployee(employee);
                    UnitOfWork.Current.Flush();
                }
                return RedirectToAction("SelectEmployees");
            }
            return View("EditEmployee", employee);
        }

Open in new window

0
Comment
Question by:I_s
  • 4
  • 2
6 Comments
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 500 total points
Comment Utility
well its really hard to find an issue with hibernate xml files, i suggest you use FluentNHibernate instead and have your mappings defined in the code itself in a much typesafe way.


http://fluentnhibernate.org/
0
 

Author Comment

by:I_s
Comment Utility
I would rather use FluentNHibernate...

So I tried to install FlunetNHibernate about 3 weeks ago... but could not get the package manager to work... This is what I get everytime when attempting to install NuGet

Description
I tried uninstalling NHibernate 3.0 and still could not get past this point...

Any suggestions?
0
 

Author Comment

by:I_s
Comment Utility
Here is the install log..

Verifying matching extension signatures before updating...
Installed Extension Path: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft Corporation\NuGet Package Manager\1.2.20325.9034\
Update Extension Path: c:\users\kfeeney.amcharwholesale\downloads\nuget.tools (2).vsix
3/16/2012 3:26:37 PM - VSIXInstaller.SignatureMismatchException: The signature on the update version of 'NuGet Package Manager' does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
   at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
   at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)
3/16/2012 3:26:37 PM - Install Error : VSIXInstaller.SignatureMismatchException: The signature on the update version of 'NuGet Package Manager' does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
   at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
   at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)
3/16/2012 3:26:37 PM - Verifying matching extension signatures before updating...
Installed Extension Path: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\VWDExpressExtensions\Microsoft Corporation\NuGet Package Manager\1.2.20325.9034\
Update Extension Path: c:\users\kfeeney.amcharwholesale\downloads\nuget.tools (2).vsix
3/16/2012 3:26:37 PM - VSIXInstaller.SignatureMismatchException: The signature on the update version of 'NuGet Package Manager' does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
   at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
   at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)
3/16/2012 3:26:37 PM - Install Error : VSIXInstaller.SignatureMismatchException: The signature on the update version of 'NuGet Package Manager' does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
   at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
   at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:I_s
Comment Utility
Ok... sooo the logs tell me that I already have it installed haha. I should have noticed that earlier... I will try with fluent
0
 

Author Comment

by:I_s
Comment Utility
Anyone know of a good tutorial for using Fluent NHibernate with ASP.NET MVC3 ??
0
 
LVL 20

Expert Comment

by:BuggyCoder
Comment Utility
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now