2

我有一个使用 nHibernate 的小型 POC 应用程序。这是我第一次自己设置 nHibernate,但我之前也使用过它。出于某种原因,我的查询没有返回任何数据。我可以确认我Product的数据库中有一个。

public class NHibernateHelper
{
    private static String _connectionString =
        @"Server=localhost\SQLEXPRESS;Database=TestProject;User ID=TestProjectMvc;Password=Pa$$word";

    private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
                InitializeSessionFactory();

            return _sessionFactory;
        }
    }

    private static void InitializeSessionFactory()
    {
        _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString).ShowSql()
            ).Mappings(m => m.FluentMappings.AddFromAssemblyOf<Product>())
            //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
            .BuildSessionFactory();
    }

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

我的映射类:

 public class ProductMap : ClassMap<Product>
 {
    public ProductMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        References(x => x.Category).Column("CategoryId");
    }
 }

我用来检索数据的方法:

    public IEnumerable<Product> GetAllProducts()
    {
        using (var session = NHibernateHelper.OpenSession())
        {
            var list = session.QueryOver<Product>().List();
            return list;
        }
    }
4

2 回答 2

4

从另一种类型的程序集中添加映射的非常有用的方法总是会绊倒其他人。

对于其他想知道的人..问题是这样的:

.AddFromAssemblyOf<Product>()

Product并且ProductMap在不同的集会中。因此,无法在Product驻留的程序集中找到映射。

我已经看到很多人开始了这次旅行!

于 2013-10-24T22:18:05.683 回答
0

此外 - 如果您使用 SchemaExport 为您生成数据库表 - /do/ 请记住在第二次运行应用程序时将其关闭。否则它对你来说又是一张空白的桌子......

于 2015-09-24T20:01:13.990 回答