zoukankan      html  css  js  c++  java
  • NH对象操作

    The preceding method creates a session factory


    Let's first create a new category object. We can do this by using the following code snippet:

    var category = new Category
    {
    Name = "Beverages",
    Description = "Some description"
    };

    Next, we want to save this new category object and we can do so by using the following code:
    var id = session.Save(category);

    The value that is returned from the save method corresponds to the ID of the newly createdcategory object.
    Now, let's create a product. The product has a reference to a category object. Before we can save a product, the corresponding category object must have been persisted to the database. The following code would work:
    var category = new Category { Name = "Beverages" };
    var product = new Product { Name = "Milk", Category = category };
    session.Save(category);
    session.Save(product);

    The session object can also be used to delete an existing object from the database. The command to do so is as simple as the following code:
    session.Delete(category);

    Here, the category object we pass as a parameter to the delete method corresponds to the one we want to remove from the database.

    Reading from the database


    Persisting data into a database is surely important, but we also want to be able to reuse this data and thus must have a means to access it. The NHibernate session object provides us with this possibility. We can use the session object directly to access a single object in the database, which is identified by its primary key by using the following code:

    var category = session.Get<Category>(1);


    NHibernate will query the database for a category record in the category table having an ID of 1. NHibernate will then take this data and create a category object from it. We also say, "NHibernate rehydrates an object".
    If we want to read not only a single object, but a list of objects from the database, we can use the LINQ to NHibernate provider to do so. The following statement will read all records from the category table and generate a list of the category objects out of it:

    var categories = session.Query<Category>();

    We can even go a step further and, for example, query a list of all discontinued products sorted by their name with the following statement:

    var products = session.Query<Product>()
    .Where(p =>p.Discontinued)
    .OrderBy(p =>p.Name);

  • 相关阅读:
    怎么点击div之外的区域就隐藏这个div啊 找了很久,都没有很好解决
    ibatis 到 MyBatis区别
    MyBatis学习(一)一个简单的例子
    iBatis简单入门教程
    strut2的标签
    spring事务传播机制实例讲解
    ORACLE中Drop table cascade constraints之后果.
    oracle表的操作sql语句
    webService
    Oracle临时表
  • 原文地址:https://www.cnblogs.com/TivonStone/p/2394130.html
Copyright © 2011-2022 走看看