【问题标题】:Can't Seem to get my data out of MySQL DB with NHibernate似乎无法使用 NHibernate 从 MySQL DB 中获取我的数据
【发布时间】:2011-05-09 08:22:48
【问题描述】:

所以我已经设置了一个带有一条记录的表的 MySQL 数据库。我的解决方案由三个项目(1 个领域模型库、测试库和我的 Web 项目)组成。在我的 MVC 项目中,我使用所有必要的 Dll 实现了 NHibernate,并且

在 Web 项目根目录中:

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 正在向我的控制器传递一个对象 产品控制器.cs 公共类 ProductsController : 控制器 { 私有只读 IProductsRepository productsRepository;

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

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

}

NinjectControllerFactory.cs 公共类 NinjectControllerFactory : DefaultControllerFactory { //提供对象实例 私有 IKernel 内核 = 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);
}

}

您将出售的服务类调用我的服务类 DaisyblossomsServices: 公共类 DaisyblossomsServices : NinjectModule {

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

}

您可以在哪里看到 IProductsRepository 绑定到我的 ProductsRepository 类:

public class ProductsRepository : IProductsRepository

{ 公共 IQueryable 产品 { 获取 { var session = BootStrapper.GetSession();

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

    }
}

}

我的 ProductsController 被交给了一个 IProductsRepository 对象

 public interface IProductsRepository

{ 可查询产品 { 获取; } }

作为附加信息,我的 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>

Web.config 中我的 connectionsStrings 部分:

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

有什么想法可能是我的问题吗?

【问题讨论】:

  • 哦,没有错误。很明显,它没有从数据库中检索任何要显示的记录。
  • 抱歉遗漏了我的 ASPX 页面:我只是 foreach(模型中的 var product)并显示 product.Name 以及 Product.Price.ToString("c")
  • 最后,如果我更改连接字符串中的密码,它会出错并返回“拒绝访问该用户。所以我假设它正在使用正确的凭据连接到数据库。为什么不是返回记录是问题所在。

标签: mysql nhibernate model-view-controller


【解决方案1】:

验证 hibernate.cfg.xml 是否将输出设置为“如果较新则更新”并且您的 *.hbm.xml 文件被标记为嵌入式资源。这是最常见的两个错误。听起来您也正试图让许多活动部件同时工作。您可能想要简化一些事情,只需要一个控制台应用程序来使用 NHibernate 连接到 MySQL。像这样的:

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();
    }
}

这将允许您验证您的映射和配置文件是否正确,而无需同时担心 MVC、Ninject 等。

【讨论】:

  • cfg.xml 和 .config 文件一样吗?我见过两者都被引用,但从来没有在同一个项目中?
  • 如果您将配置文件命名为 hibernate.cfg.xml,NHibernate 会在您不带任何参数地调用 cfg.Configure() 时自动加载它。如果要将配置文件命名为其他任何名称,则需要指定文件名。所以是的,它们是一样的。
猜你喜欢
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 2018-01-16
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多