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);

  • 相关阅读:
    怎样做到长期写一个价值博客?
    linux中rz、rs命令无法执行的情况
    关于图床的选择方案(博客园、公众号、简书、CSDN)
    如何有效地记录和管理笔记(一)
    Linux之时间同步操作
    weblogic12.1.3 静默安装 建域
    在Linux 系统上运行多个tomcat
    Python 生成随机数
    异常处理

  • 原文地址:https://www.cnblogs.com/TivonStone/p/2394130.html
Copyright © 2011-2022 走看看