0
votes

So I have setup a MySQL database with table with one record. My Solution is made up of three projects (1 domain model library, test library and my Web project). In my MVC project I have implemented NHibernate with all necessary Dll's, and

In Web project root:

nhibernate-configuration.xsd
nhibernate-mapping.xsd
nhibernate.config and 
<classname>.hbm.xml file - with the class it is mapping

In my Global.asax.cs file I have my event handlers to bind the current session: public class MvcApplication : System.Web.HttpApplication {

public MvcApplication()
{
  BeginRequest += (MvcApplication_BeginRequest);
  EndRequest += (MvcApplication_EndRequest);
}

void MvcApplication_BeginRequest(object sender, EventArgs e)
{
  CurrentSessionContext.Bind(BootStrapper.SessionFactory.OpenSession());
}

void MvcApplication_EndRequest(object sender, EventArgs e)
{
  CurrentSessionContext.Unbind(BootStrapper.SessionFactory).Dispose();
}

Then I have my BootStrapper class which returns the current session: public static readonly ISessionFactory SessionFactory = CreateSessionFactory();

  private static ISessionFactory CreateSessionFactory()
  {
    var cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nhibernate.config"));
    cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
    return cfg.BuildSessionFactory();
  }

  public static ISession GetSession()
  {
    return SessionFactory.GetCurrentSession();
  }

My Controller is being handed an object by my Ninject IoC ProductController.cs public class ProductsController : Controller { private readonly IProductsRepository productsRepository;

    public ProductsController(IProductsRepository productsRepository)
    {
      this.productsRepository = productsRepository;
    }

    public ViewResult List()
    {
        return View(productsRepository.Products.ToList());
    }

}

NinjectControllerFactory.cs public class NinjectControllerFactory : DefaultControllerFactory { //Supplies Object instances private IKernel kernel = new StandardKernel(new DaisyblossomsServices());

//MVC calls this to get the controller for each requests
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
  if (controllerType == null)
    return null;
  return (Controller)kernel.Get(controllerType);
}

}

Which you will sell calls my services class DaisyblossomsServices: public class DaisyblossomsServices : NinjectModule {

public override void Load()
{
    Bind<IProductsRepository>().To<ProductsRepository>();
}

}

Where you can see IProductsRepository is bound to my ProductsRepository class:

public class ProductsRepository : IProductsRepository

{ public IQueryable Products { get { var session = BootStrapper.GetSession();

    return session.CreateCriteria(typeof(Product)).List<Product>().AsQueryable();

    }
}

}

And my ProductsController is handed an IProductsRepository object

 public interface IProductsRepository

{ IQueryable Products { get; } }

As additional information My Product.hbm.xml file which maps my Product.cs class

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="Daisyblossoms.Domain"
                   namespace="Daisyblossoms">
      <class name="Product"
         table="product">
    <id name="ProductID">
      <generator class="assigned" />
    </id>
    <property name="Name" column="Name" />
    <property name="Price" column="Price" />
  </class>
</hibernate-mapping>

And my nhibernate.config:

<?xml version="1.0"?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory name="Daisyblossoms.Domain">
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
    <property name="generate_statistics">true</property>
    <property name="current_session_context_class">web</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory,     NHibernate.ByteCode.Castle</property>
    <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
    <mapping assembly="Daisyblossoms.WebUI"/>
  </session-factory>
</hibernate-configuration>

And my connectionsStrings part of Web.config:

<connectionStrings>
<add name="daisyblossoms" connectionString="Server=localhost;Port=3306;Database=dbName;Uid=user;Pwd=somePSWD;pooling=false;" 
 providerName="MySql.Data.MySqlClient"/>

Any thoughts what might be my issue?

1
Oh, and no errors. Its obvious it isn't retrieving any records from the DB to display.pghtech
Sorry left out my ASPX page: I just foreach (var product in Model) and display product.Name as well as Product.Price.ToString("c")pghtech
And finally, if I change the password in the connectionString, it will error and return "Access denied for that user. So I assume it is connecting to the DB, with the correct credentials. Why it's not returning the record is the problem.pghtech

1 Answers

1
votes

Verify that hibernate.cfg.xml has output set to "Update if newer" and that your *.hbm.xml files are marked as Embedded Resources. Those are the two most common mistakes. It also sounds like you're trying to get a lot of moving parts working at the same time. You might want to simplify things to just get a console app to connect to MySQL using NHibernate. Something like this:

internal class Program {
    private static void Main() {
        var cfg = new Configuration();
        cfg.Configure();  // Uses hibernate.cfg.xml by default.
        // cfg.Configure("nhibernate.config");  // Or use this overload if you prefer your own name.
        var sessionFactory = cfg.BuildSessionFactory();
        using(var session = sessionFactory.OpenSession())
        using(var tx = session.BeginTransaction()) {
            var query = session.CreateCriteria<Product>().List();
            query.ForEach(x => Console.WriteLine(x.Name));
            tx.Commit();
        }
        Console.WriteLine("Press <ENTER> to exit...");
        Console.ReadLine();
    }
}

This would allow you to verify that your mappings and configuration files are correct without worrying about MVC, Ninject, etc. at the same time.