我有一个非常简单的实体:
public class Days
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
}
地图类
public class DaysMap : ClassMap<Days>
{
public DaysMap()
{
Table("Days");
Id(x => x.ID).GeneratedBy.Identity().Column("ID");
Map(x => x.Name).Column("Name");
}
}
这是测试,我想用ID = 1
加载Day
。我可以加载该项目,但需要的时间=2,5s!这是存储在localhost上的MySQL数据库。
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString("server=localhost;user id=someID;password=pass;database=someDB"))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.BuildSessionFactory();
}
public ActionResult Index()
{
Stopwatch sw = new Stopwatch();
sw.Start();
using (var sessionFactory = CreateSessionFactory())
{
using (var session = sessionFactory.OpenSession())
{
using (session.BeginTransaction())
{
var asd = session.Query<Days>().Where(x => x.ID == 1).FirstOrDefault();
}
}
}
sw.Stop();
var timeElapsed = sw.Elapsed.TotalMilliseconds; // returns 2504.3316 !!
return View();
}
希望您不会每次都做以下操作:
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString("server=localhost;user id=someID;password=pass;database=someDB"))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.BuildSessionFactory();
}
每个应用程序只能创建SessionFactory一次。在确定查询需要多长时间时,不能包含此时间。通常,我会在应用程序启动时提前构建它,以避免由于尚未构建而导致初始查询耗时过长。这是使用NHibernate时非常常见的做法。