C# FluentNHibernate 连接mysql数据库

发表于2018-08-03
评论0 3.5k浏览
Fluent NHibernate 提供一个替代 NHibernate 的标准 XML 映射文件的方法,它可以让你在强类型 C# 代码中编写映射。这会易于重构、提高可读性并且会有更简洁的代码。下面大家看到的是如何使用Fluent NHibernate去连接mysql数据库。

首先需要安装FluentNHibernate包,右键工程文件

右键项目工程,如下图,在打开的窗口中下载NHibernate包,并安装。  


程序代码:  

连接数据库: 
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数据库
{
    class NHibernateHelper
    {
        private static ISessionFactory sessionFactory = null;
        private static void InitializeSessionFactory()
        {
            sessionFactory = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(db => db
                    .Server("127.0.0.1")
                    .Database("mydb")
                    .Username("root")
                    .Password("")))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>())
                    .BuildSessionFactory();
        }
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    InitializeSessionFactory();
                }
                return sessionFactory;
            }
        }
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

创建实体类  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数据库.DB
{
    class User
    {
        public virtual int id { get; set; }
        public virtual string account { get; set; }
        public virtual string password { get; set; }
    }
}

映射类  
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数据库.DB
{
    class UserMap:ClassMap<User>
    {
       public UserMap() {
           this.Id(db => db.id).Column("id");
           this.Map(db => db.account).Column("account");
           this.Map(db => db.password).Column("password");
           this.Table("user");
        }
    }
}

创建数据库操作类  
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数据库.DB
{
    class UserManage
    {
        public static UserManage Instance = new UserManage();
        /// <summary>
        /// 通过账号和密码查看用户是否存在
        /// </summary>
        /// <param name="uName">账号</param>
        /// <param name="psw">密码</param>
        /// <returns></returns>
        public User Login(string uName, string psw)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction ita = session.BeginTransaction())
                {
                    var iq = session.QueryOver<User>().Where(user => user.account == uName && user.password == psw);
                    IList<User> res = iq.List();
                    if (res.Count > 0)
                    {
                        return res[0];
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 通过账号和密码添加新的用户
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool add(string account, string password)
        {
            bool flag = false;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction ita = session.BeginTransaction())
                {
                    User user = new User();
                    user.account = account;
                    user.password = password;
                    Object obj = session.Save(user);
                    ita.Commit();
                    if (obj != null)
                    {
                        flag = true;
                    }
                }
            }
            return flag;
        }
        /// <summary>
        /// 通过账号删除用户
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool Delete(string account, string password)
        {
            bool flag = false;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction ita = session.BeginTransaction())
                {
                    try
                    {
                        session.Delete("From User Where account='" + account + "' and password");
                        ita.Commit();
                        flag = true;
                    }
                    catch (Exception)
                    {
                        flag = false;
                    }
                }
            }
            return flag;
        }
        /// <summary>
        /// 通过账号和旧的密码更新新的密码
        /// </summary>
        /// <param name="oldAccount">账号</param>
        /// <param name="oldPassword">旧的密码</param>
        /// <param name="mewPassword">新的密码</param>
        /// <returns></returns>
        public bool Updata(string oldAccount, string oldPassword,string newPassword)
        {
            bool flag = false;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction ita = session.BeginTransaction())
                {
                    try
                    {
                        string sql = "UPDATE user SET password='" + newPassword + "' WHERE (account='"+oldAccount+"' and password='"+oldPassword+"')";
                        ISQLQuery query = session.CreateSQLQuery(sql);
                        int ret=query.ExecuteUpdate();
                        Console.WriteLine("updata res="+ret);
                        ita.Commit();
                        flag = true;
                    }
                    catch (Exception)
                    {
                        flag = false;
                    }
                }
            }
            return flag;
        }
    }
}

程序运行结果图  
来自:https://blog.csdn.net/u011484013/article/details/51221074

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引