2015-02-11 91 views
0

我有一个非常简单的实体:流利NHibernate的很慢的查询执行(DB托管在本地主机)

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

和这里的测试,我想加载DayID = 1。我可以加载该项目,但需要的时间= 2,5s!这是存储在本地主机上的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(); 
    } 

回答

1

希望你不是在做每一次执行以下操作:

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只应每个应用程序1次。确定查询需要多长时间时,您不能包含此时间。通常我会在应用程序启动时进行构建,以消除初始查询需要花费的时间,因为我还没有构建它。在使用NHibernate时这是很常见的做法。