我有一个使用 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;
}
}