第一个NHibernate应用程序(二)

增删改查询

 

using NHibernate;
using Shop.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Shop.Data
{
    public class CartData
    {
        /// <summary>
        /// 根据条件得到数据集合
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IList<Cart> GetCartList(Expression<Func<Cart,bool>> where)
        {
            try
            {
                using (ISession session = NHibernateHelper.SessionFactory.OpenSession())
                {
                    return session.Query<Cart>().Select(x=>new Cart
                    {
                        Id = x.Id,
                        Name = x.Name
                    }).Where(where).ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取单条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Cart GetCartById(int id)
        {
            using (ISession session = NHibernateHelper.SessionFactory.OpenSession())
            {
                Cart cart = session.Get<Cart>(id);
                return cart;
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="cart"></param>
        /// <returns></returns>
        public bool Insert(Cart cart)
        {
            using (var session = NHibernateHelper.SessionFactory.OpenSession())
            {
                var identifier = session.Save(cart);
                session.Flush();
                return string.IsNullOrEmpty(identifier.ToString());
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="cart"></param>
        public void Update(Cart cart)
        {
            using (var session = NHibernateHelper.SessionFactory.OpenSession())
            {
                session.SaveOrUpdate(cart);
                session.Flush();
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            using (var session = NHibernateHelper.SessionFactory.OpenSession())
            {
                var cart = session.Get<Cart>(id);
                session.Delete(cart);
                session.Flush();
            }
        }


    }
}

 参阅:ASP.NET MVC 企业级实战(邹琼俊

posted @ 2019-03-03 22:03  蜗牛的礼物  阅读(101)  评论(0编辑  收藏  举报