Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2012-03-16
6
Medium Priority
?
355 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 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
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.

 

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

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

927 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