一次将 1000 多条记录保存到数据库中 [英] Saving 1000+ records to the database at a time

查看:35
本文介绍了一次将 1000 多条记录保存到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 NHibernate.我有一种情况,我需要像这样将一堆记录保存到数据库中:

I'm using NHibernate currently. I have a situation where I need to save a bunch of records to the database like this:

var relatedTopics = GetRelatedTopics(topic);
foreach (var relatedTopic in relatedTopics /* could be anywhere from 10 - 1000+ */)
{
    var newRelatedTopic = new RelatedTopic { RelatedTopicUrl = relatedTopic, TopicUrl = topic.Name };
    _repository.Save(newRelatedTopic);
}

当有大量记录要保存时,必须多次访问数据库显然非常费力.有什么更好的方法?我可以做某种批量更新吗?我最好使用 DataSet 吗?

When there are a ton of records to save this is obviously very taxing having to hit the database that many times. What's a better approach? Is there some sort of batch update I can do? Am I better off using a DataSet?

谢谢

推荐答案

设置 adonet.batch_size 可以改善这种情况.

setting adonet.batch_size could improve the situation.

你必须这样做

  • 在 NH 配置中设置 adonet.batch_size

例子:

    m_sessionFactory = Fluently
         .Configure()
         .Database(MsSqlConfiguration
             .MsSql2005
             .ConnectionString(c => c.FromConnectionStringWithKey("testme"))
             )
         .Mappings(m => m.FluentMappings
             .AddFromAssemblyOf<TestImpl>())
         .ExposeConfiguration(config =>
         {
             config.SetProperty("adonet.batch_size", "1");
             m_configuration = config;
         })
         .BuildSessionFactory();

  • 在保存前设置会话的批量大小

    • set the batch size on the session just before the save

      using (ISession session = m_nhibernateSessionFactory.GetSession())
      using (var tx = session.BeginTransaction())
      {    
         session.SetBatchSize(1000);     
         foreach (var server in serverz)
         {
            session.SaveOrUpdate(server);
         }
         tx.Commit();
      }
      

    • 这篇关于一次将 1000 多条记录保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆