Итак, я настроил базу данных MySQL с таблицей с одной записью.Мое решение состоит из трех проектов (1 библиотека модели домена, тестовая библиотека и мой веб-проект).В моем проекте MVC я реализовал NHibernate со всеми необходимыми библиотеками DLL и
В корне веб-проекта:
nhibernate-configuration.xsd
nhibernate-mapping.xsd
nhibernate.config and
<classname>.hbm.xml file - with the class it is mapping
В моем файле Global.asax.cs у меня есть обработчики событий для привязкитекущий сеанс: открытый класс 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();
}
Затем у меня есть класс BootStrapper, который возвращает текущий сеанс: 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();
}
Мой контроллер получает объект от моего открытого класса Ninject IoC ProductController.cs ProductsController: Controller {private readonly IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
NinjectControllerFactory.cs открытый класс NinjectControllerFactory: DefaultControlFэкземпляры частного ядра IKernel = новый 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);
}
}
который вы будете продавать, называет мой класс служб DaisyblossomsServices: открытый класс DaisyblossomsServices: NinjectModule {
public override void Load()
{
Bind<IProductsRepository>().To<ProductsRepository>();
}
}
Где вы можете видеть, IProductsRepository связан с моим классом ProductsRepository:
public class ProductsRepository : IProductsRepository
{public IQueryable Products {get {var session = BootStrapper.GetSession ();
return session.CreateCriteria(typeof(Product)).List<Product>().AsQueryable();
}
}
}
А моему ProductsController передан объект IProductsRepository
public interface IProductsRepository
{IQueryable Products {get;}}
В качестве дополнительной информации Файл My Product.hbm.xml, который сопоставляет мой класс Product.cs
<?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>
И мой 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>
Имои соединенияStrings часть Web.config:
<connectionStrings>
<add name="daisyblossoms" connectionString="Server=localhost;Port=3306;Database=dbName;Uid=user;Pwd=somePSWD;pooling=false;"
providerName="MySql.Data.MySqlClient"/>
Есть мысли, что может быть моей проблемой?