Solved

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

Posted on 2012-03-16
6
343 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 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

737 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