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

  • 相关阅读:
    青松云安全-WAF-1.0.655 (ubuntu 14.04 server)
    相似变换和仿射变换
    参数坐标系统变换
    城市测量坐标系统的建立
    工程测量坐标系
    大地测量控制点坐标转换技术规范
    为什么样本方差(sample variance)的分母是 n-1?
    似大地水准面
    typedef的用法
    同一椭球面经纬度坐标与空间直角坐标之间的相互转换
  • 原文地址:https://www.cnblogs.com/TivonStone/p/2394130.html
Copyright © 2020-2023  润新知