简体   繁体   English

Nhibernate 保存对象的顺序

[英]Nhibernate order of saving objects

I'm having a service which takes a one or more of entities, which has been deserialized from a file.我有一项服务,它需要一个或多个实体,这些实体已从文件中反序列化。 These entities may or may not have a relation.这些实体可能有也可能没有关系。 Are there any easy way to ensure that Nhibernate handles the entities in the correct order when calling saving the entities?有没有什么简单的方法可以确保 Nhibernate 在调用保存实体时以正确的顺序处理实体? Right now I'm doing it with session.Save(entity) , but it may end up some times end up with an exception about " property pointing at a transient or null value.." .现在我正在使用session.Save(entity)来做它,但有时它可能最终会出现一个关于“属性指向一个瞬态或空值..”的异常。

In general, no, NHibernate will manage it for you automatically because it is considered the safe way.一般来说,不,NHibernate 会自动为您管理它,因为它被认为是安全的方式。 There are two options:有两种选择:

First option : You can perform a Flush method and make sure you have the executed over the database.第一个选项:您可以执行Flush方法并确保已在数据库上执行。 For sample:样品:

using (var session = sessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        try
        {
            foreach (var item1 in data1)
            {
                session.Save(item1);
            }
            session.Flush(); // execute all the queries for the itens (1)

            foreach (var item2 in data2)
            {
                session.Save(item2);
            }
            session.Flush(); // execute all the queries for the itens (2)

            transaction.Commit();
        }
        catch (Exception e)
        {   
            transaction.RollBack();
            // do some log with `e` exception reference
        }
    }
}

Second option .第二种选择 If you just need to send it to the database without any state management, you could use ISessionStateless instead of classical ISession .如果您只需要在没有任何状态管理的情况下将其发送到数据库,您可以使用ISessionStateless而不是经典的ISession You lose all the sesion state management that NHibernate does automatically.您将失去 NHibernate 自动执行的所有会话状态管理。 (lazy loading, first/second level caching, etc..). (延迟加载、一级/二级缓存等)。 You just call method like Insert , Delete , Update a entity.您只需调用方法,如InsertDeleteUpdate一个实体。 Importante: You can have more performance with a StatelessSession give you make sure it is appropriate for your scenario:重要提示:您可以通过StatelessSession获得更高的性能,以确保它适合您的场景:

https://nhibernate.info/doc/nhibernate-reference/batch.html https://nhibernate.info/doc/nhibernate-reference/batch.html

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

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