
_START_ARTICLE_
NHibernate
_START_SECTION_
例子
_START_PARAGRAPH_
这里有程式码片段，是要使用NHibernate将物件加入数据库，和展示如何取得、修改、更新数据库中的物件。_NEWLINE_//Add a Customer to the datastore//'sessionFactory' is a thread-safe object built once per application lifetime (can take seconds to build)//based on configuration files which control how database tables are mapped to C# objects//(e.g. which property maps to which column in a database table)////'session' is not thread safe and fast to obtain and can be thought of as a connection to the databaseusing (var session = sessionFactory.OpenSession()) _NEWLINE_{_NEWLINE_    //transaction represents a db transaction_NEWLINE_    using (ITransaction transaction = session.BeginTransaction()) _NEWLINE_    {_NEWLINE_        //The line below adds the customer to NHibernate's list of objects to insert to the database_NEWLINE_        //but it doesn't execute SQL insert command at this stage*._NEWLINE_        //*if the Id field is generated by the database (e.g. an auto-incremented number) _NEWLINE_        //then NHibernate will execute SQL INSERT when .Save is called  _NEWLINE_        session.Save(new Customer { Id = Guid.NewGuid(), FirstName = "Boss", Age = 50 });_NEWLINE__NEWLINE_        //The call below will execute the SQL INSERT and commit the transaction_NEWLINE_        transaction.Commit();_NEWLINE_    }}//Retrieve the Customer from the database, modify the record and update the databaseusing (var session = sessionFactory.OpenSession()){_NEWLINE_    using (ITransaction transaction = session.BeginTransaction()) _NEWLINE_    {_NEWLINE_        //session's Query returns IQueryable<Customer>._NEWLINE_        //Only when .FirstOrDefault is called will NHibernate execute the SQL query  _NEWLINE_        Customer customer = session.Query<Customer>().Where(c => c.Token == token ).FirstOrDefault();_NEWLINE_    _NEWLINE_        //Now the customer is 'part of' the 'session' object and NHibernate keeps track of changes_NEWLINE_        //made to it _NEWLINE_        if( customer != null ) _NEWLINE_        {_NEWLINE_            //Changing a property of an object does NOT cause SQL to be executed_NEWLINE_            customer.TokenVerified = true;_NEWLINE_    _NEWLINE_           //Committing the transaction results in an SQL UPDATE statement_NEWLINE_           //NHibernate kept track of the fact that 'customer' has been changed since loading _NEWLINE_           transaction.Commit();_NEWLINE_        }_NEWLINE_    }}_NEWLINE_NHibernate's configuration may affect when NHibernate executes SQL statements.