0

I would like to use NHibernate in an MVC application I'm working on, and I'm having trouble with the configuration. I'm using a setup I found on this blog.

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory
    {
        get 
        {
            if (_sessionFactory == null)
            {
                var NHibernateConfig = new Configuration();
                NHibernateConfig.Configure(HttpContext.Current.Server.MapPath(@"Models\NHibernate\hibernate.cfg.xml"));
                NHibernateConfig.AddDirectory(new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(@"Models\NHibernate\Mapping")));
                _sessionFactory = NHibernateConfig.BuildSessionFactory();
            }

            return _sessionFactory;
        }  
    }

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

I've been fiddling a bit with the application trying to get the connection working, and now I'm getting an error at the following line:

NHibernateConfig.Configure(HttpContext.Current.Server.MapPath(@"Models\NHibernate\hibernate.cfg.xml"));

The error is below.

{"Could not find a part of the path 'C:\\Users\\%username%\\Documents\\Visual Studio 2010\\Projects\\Helpdesk4\\Helpdesk4\\Ticket\\Models\\NHibernate\\hibernate.cfg.xml'."}

I can see clearly where the problem is. There is no "Ticket" directory. It should go ...Helpdesk4\\Helpdesk4\\Models\\.... But I have no idea why the MapPath thinks that should be part of the path.

If it helps, here are some details from my _Layout.cshtml and TicketController files:

TicketController

    public ActionResult TicketLog()
    {
        IList<Ticket> lstTickets = _repository.getTickets();
        return View(lstTickets);
    }

Layout:

                 <nav>
                    <ul id="menu">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        <li>@Html.ActionLink("Ticket Log", "TicketLog", "Ticket")</li>
                    </ul>
                </nav>
4

1 回答 1

1

Server.MapPath 使用来自您的请求的相对路径 - 所以如果您的第一个请求是 to /Tickets,那么Server.MapPath(@"Models\NHibernate\hibernate.cfg.xml")将相对于/Tickets- 因此/Tickets/Models/等...

只需将其更改为Server.MapPath(@"~\Models\NHibernate\hibernate.cfg.xml"),它应该会找到配置文件 -"~\"告诉它从应用程序的根目录映射它

于 2013-09-13T16:20:40.393 回答