Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2012-03-16
6
Medium Priority
?
353 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 1500 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
Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

 

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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

722 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