流利的Nhibernate查询执行非常慢(在localhost上托管数据库)

时间:2015-02-11 16:02:43

标签: mysql fluent-nhibernate

我有一个非常简单的实体:

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

这是测试,我想用Day加载ID = 1。我可以加载该项目,但需要时间= 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();
    }

1 个答案:

答案 0 :(得分: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。在确定查询所需的时间时,您不能包含此时间。通常我会在应用程序启动时预先构建它,以消除初始查询需要永远,因为我还没有构建它。这在使用NHibernate时非常常见。