简体   繁体   English

使用Fluent NHibernate批量插入实体集合

[英]Inserting a collection of entities in bulk using Fluent NHibernate

I'm trying to insert a large collection of objects into a table using fluent NHibernate, using a call to save or update passing each entity from the collection in a foreach loop. 我正在尝试使用流畅的NHibernate将大量对象插入到表中,使用调用来保存或更新在foreach循环中从集合中传递每个实体。 I had been setting the batch size to the size of the collection, however I've read on Ayende's blog that setting it to large values is not recommended so I've capped it at 250, however when I view the collection in NHProf, I see a stream of insert statements (the collection is about 20000 items) rather than a set of batched insert calls. 我已经将批量大小设置为集合的大小,但是我已经在Ayende的博客上看到,不建议将其设置为大值,因此我将其限制为250,但是当我在NHProf中查看集合时,我查看插入语句流(该集合大约是20000个项目)而不是一组批量插入调用。

This seems very inefficient and is taking a far longer time than I'd expect for a query that is very basic in essence - inserting a value into 25 columns (yes, that is one place this could be made better, but it's a legacy database that I'm stuck with for now) into a SQL Server 2008 database - so I can only assume I'm doing it wrong. 这似乎非常低效,并且花费的时间比我期望的查询本质上非常基本 - 将值插入25列(是的,这是一个可以做得更好的地方,但它是遗留数据库)我现在仍然坚持到SQL Server 2008数据库 - 所以我只能假设我做错了。

Is there a recommended way to insert large collections of entities using NHibernate? 是否有推荐的方法使用NHibernate插入大型实体集合? Is there an efficiency gain to be had by using Save over SaveOrUpdate? 使用Save over SaveOrUpdate可以提高效率吗?

Code of the add method - the SetBatchSize call is where the batch is capped to 250, or set to the collection size if it's less than 250: add方法的代码 - SetBatchSize调用是批处理上限为250的位置,或者如果小于250则设置为集合大小:

public void Add(IEnumerable<TEntity> entities)
{
    var session = GetCurrentSession();
    using (var transaction = session.BeginTransaction())
    {
        entities = entities.ToList();

        session.SetBatchSize(SetBatchSize(entities.Count()));

        foreach (var entity in entities)
            session.SaveOrUpdate(entity);

        transaction.Commit();
    }
}

Apologies for the slightly vague question, I get the feeling I'm just approaching things the wrong way and any pointers would be greatly appreciated! 对于稍微模糊的问题道歉,我感觉我只是以错误的方式接近事情而且任何指针都会非常感激!

You'll want to use a StatelessSession for bulk inserts. 您将要使用StatelessSession进行批量插入。

(related: Inserts of stateless session of NHibernate are slow ) (相关: NHibernate无状态会话的插入很慢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM