Search in Fluent-NHibernate using session.QueryOver<> return empty

1.3k views Asked by At

Hey everyone I am new to ORM, Im using Fluent NHibernate in my CRUD seems to have a problem in my search, it will return an empty or null value and also I can insert data, but when i insert another record its seems updating bcoz it replace my previous record. I try doing some google but still no used. Can anyone give me some tutorial links.

My Code:

employee Class in objclass folder

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;

  namespace fluent.objclass
  {
     public class employees
     {
        public virtual int employee_id { get; set; }
        public virtual string employee_code { get; set; }
        public virtual string last_name { get; set; }
        public virtual string first_name { get; set; }
        public virtual string middle_initial { get; set; }
        ect..
     }
  }

My Mapping Class in map class folder

  using fluent.objclass;
  using FluentNHibernate.Mapping;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;

 namespace fluent.mapclass
 {
 public class employeesMap: ClassMap<employees>
 {
    public employeesMap() 
    {
        Id(x => x.employee_id);
        Map(x => x.employee_code);
        Map(x => x.last_name);
        Map(x => x.first_name);
        Map(x => x.middle_initial);
        ect..
      }
   }
 }

My Repository in repository folder

using fluent.objclass;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace fluent.repository
{
public class emp_repository
{
    public void INSERT(employees newEmp) 
    {
        using (ISession session = NHibernateHelper.OpenSession()) 
        {
            using (ITransaction transaction = session.BeginTransaction()) 
            {
                session.Save(newEmp);
                transaction.Commit();
            }
        }

    }

    public employees GetemployeesbyLName(int input) 
    {
        using (ISession session = NHibernateHelper.OpenSession()) 
        {
            var result = session.QueryOver<employees>().Where(x =>  x.employee_id == input).SingleOrDefault();
            return result ?? new employees(); 
        }
    }
  }
}

My NHibernateHelper

using fluent.objclass;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

 namespace fluent
 {
   public class NHibernateHelper
  {
    private static ISessionFactory _sessionFactory;
    private static ISessionFactory SessionFactory
    {

        get
        {
            if (_sessionFactory == null)
                InitializeSessionFactory();

            return _sessionFactory;
        }
    }

    private static void InitializeSessionFactory()
    {
        _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012
                         .ConnectionString(@"Server=ARK\DARKAGE;Database=PNH;Trusted_Connection=True;")
                        .ShowSql()
            )
            .Mappings(m =>
                      m.FluentMappings
                            .AddFromAssemblyOf<employees>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                    .Create(true, true))
            .BuildSessionFactory();
      }

      public static ISession OpenSession()
      {
        return SessionFactory.OpenSession();

      }
  }

}

my code snipe

   using FluentNHibernate.Mapping;
   using fluent.objclass;
   using System;
   using System.Collections.Generic;
   using System.ComponentModel;
   using System.Data;
   using System.Drawing;
   using System.Linq;
   using System.Text;
   using System.Threading.Tasks;
   using System.Windows.Forms;
   using NHibernate.Linq;
   using fluent.repository;

   namespace fluent
   {
      public partial class fluent : Form
      {
         emp_repository repo = new emp_repository();
         public fluent()
         {
             InitializeComponent();
         }

         private void bntADD_Click(object sender, EventArgs e)
         {
                var emp = new employees
                {
                    employee_code = txtBAR.Text.Trim(' '),
                    last_name = txtLNM.Text.Trim(' '),
                    first_name = txtFNM.Text.Trim(' '),
                    middle_initial = txtMNM.Text.Trim(' '),
                    ect...
                };
                repo.INSERT(emp);
                MessageBox.Show(txtLNM.Text.Trim(' ') + "Successfully Added To Record");
    }

      private void bntSE_Click(object sender, EventArgs e)
      {
        employees emp = repo.GetemployeesbyLName(1);
        MessageBox.Show(emp.last_name);
      }

    }
  }

Finally my Table

 USE [PNH]
 GO
 SET ANSI_NULLS ON
 GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[employees](
[employee_id] [int] IDENTITY(1,1) NOT NULL,
[employee_code] [nvarchar](255) NULL,
[last_name] [nvarchar](255) NULL,
[first_name] [nvarchar](255) NULL,
[middle_initial] [nvarchar](255) NULL,
ect...
  PRIMARY KEY CLUSTERED 
  (
   [employee_id] ASC
   )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
   ) ON [PRIMARY]

  GO

:( sorry for my poor english and alignment :( Thanks in advance

2

There are 2 answers

2
kayess On BEST ANSWER

On first sight, I actually noticed two possible problems with your code.

First:

Have you tried to profile your generated SQL? With a profler tool like NHProf.

Edit:

Another option for logging could be, if you extend the FluentConfiguration setup by adding:

.Diagnostics(d => d.Enable(true))
.Diagnostics(d => d.OutputToConsole())

Where as the first line enables conditional logging, the second line sets diagnostic logging to console.

So then you could really see what is going on in the background, as i doubt its actually replacing your existing record.

Since you are calling the Save() method which

Persists the given transient instance

However you are stating that it gets "replaced", which would be equivalent to call SaveOrUpdate() method which

Either Save() or Update() the given instance, depending upon the value of its identifier property.

Second:

Do you need to create the whole database schema each time you instantiate your NHibernate helper?

Because you are calling the ExposeConfiguration() method with SchemaExport.Create(true, true).

Where SchemaExport.Create(...)

Runs the schema creation script

By passing the second boolean parameter to Create(), you are actually telling to execute the creation of the schema.

In short this means it will drop and re-create tables on every run.

So if you are connecting to already existing schema, you could comment out the SchemaExport call, unless you are using this for example in-memory sql server.

Hope it helps!

P.s.: quotes taken from Fluent Nhibernates XMLdoc signatures.

0
Blaire Andaloc On

My Error is in NHibernateHelper.cs in

     ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true); 

Every I run and execute it will drop the current table and recreate thats why my search returns empty and my add replaces every time I add a new entries

my Correct NHibernateHelper.cs

 using fluent.objclass;
 using FluentNHibernate.Cfg;
 using FluentNHibernate.Cfg.Db;
 using NHibernate;
 using NHibernate.Tool.hbm2ddl;
 using System.Collections.Generic;
 using System.Linq;
 using System.Reflection;
 using System.Text;
 using System.Threading.Tasks;

   namespace fluent
   {
   public class NHibernateHelper
   {
    private static ISessionFactory _sessionFactory;
    private static readonly object factorylock = new object();
    private static ISessionFactory SessionFactory
    {

        get
        {
            if (_sessionFactory == null)
                InitializeSessionFactory();

            return _sessionFactory;
        }
    }
    private static void InitializeSessionFactory()
    {
        _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012
                        .ConnectionString(@"Server=ARK\DARKAGE;Database=PNH;Trusted_Connection=True;").ShowSql()
            )
            .Mappings(m =>
                      m.FluentMappings
                            .AddFromAssembly(Assembly.GetExecutingAssembly()))
            .BuildSessionFactory();
    }

    public static ISession OpenSession()
    {
                return SessionFactory.OpenSession();
    }
  }

}