Solved

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

Posted on 2012-03-16
6
331 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
ID: 37730797
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
ID: 37730830
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
ID: 37730831
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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:I_s
ID: 37730851
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
ID: 37731129
Anyone know of a good tutorial for using Fluent NHibernate with ASP.NET MVC3 ??
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37732102
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
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 backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

831 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