搭建NHibernate3.2+CodeFirst映射框架

所用程序集:

   1,Iesi.Collections:NHibernate依赖项,用来进行集合运算。

    2,NHibernate:版本3.2.0.4000,面向.NET环境的对象/关系数据库映射工具,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去。

    3,ConfOrm:版本2.000,ConfORM是NHibernate贡献者Fabio Maulo大牛设计的,是一个配置ORM的工具,其接口按照ORM思想定义,基于GNU Lesser General Public License协议。其设计思想来源就是 ORuM(Object Relational un-Mapping)。它按照Domain定义帮助我们"自动"实现Mapping。现在仅仅实现了对NHibernate的"自动"Mapping。

映射步骤:

  1,定义实体类Student.cs

public class Student
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual int Sex { get; set; }
        public virtual int StuId { get; set; }
    }

    2,ConfOrm配置:

      这一步非常重要,是ConfORM的核心所在,实例化一个ObjectRelationalMapper对象,装配实体类对象,实例化Mapper对象,调用Mapper对象的CompileMappingFor()方法自动生成HbmMapping。

    

 public class MappingFactory
    {
        public HbmMapping CreateMapping()
        {
            var orm = new ObjectRelationalMapper();
            //主键生成策略
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());
            orm.TablePerClass(new[] { typeof(Student), typeof(NewStudent) });
            //实体关系映射
            //orm.ManyToOne<Student, Class>();
            //继承映射
            //mapper.JoinedSubclass<DatabaseTable>(cm => { cm.Key(k => { k.Column("Id"); }); });
            //mapper.JoinedSubclass<ExcelTable>(cm => { cm.Key(k => { k.Column("Id"); }); });

            //属性约束映射
            //CommonPropertyMapper(ref mapper);
            //EntityPropertyMapper(ref mapper);
            var mapper = new Mapper(orm);
            var hc = mapper.CompileMappingFor(Assembly.Load(typeof(Student).Namespace).GetTypes());
            return hc;
            //return mapper.CompileMappingFor(new[] { typeof(Student) });
        }

        ///// <summary>
        ///// 公共属性约束映射
        ///// </summary>
        ///// <param name="mapper"></param>
        //private void CommonPropertyMapper(ref Mapper mapper)
        //{
        //    //DBType mapping
        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(bool),
        //        pm => { pm.Column(cm => cm.SqlType("bit")); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(decimal),
        //        pm => { pm.Column(cm => cm.SqlType("decimal(18,2)")); });

        //    //mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(DateTime),
        //    //    pm => { pm.Column(cm => cm.SqlType("nvarchar(30)")); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(bool?),
        //        pm => { pm.Column(cm => cm.SqlType("bit")); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Email"),
        //        pm => { pm.Length(100); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("MobilePhone"),
        //        pm => pm.Length(100));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("TelPhone"),
        //        pm => pm.Length(100));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Remark"),
        //        pm => pm.Length(1000));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Description"),
        //        pm => pm.Length(1000));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Summary"),
        //        pm => pm.Length(200));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Details"),
        //        pm => pm.Length(1000));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Equals("Detail"),
        //        pm => pm.Length(8000));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Equals("Name", StringComparison.CurrentCultureIgnoreCase),
        //        pm => { pm.Length(100); pm.NotNullable(true); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Equals("Account"),
        //        pm => { pm.Length(32); pm.NotNullable(true); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Num"),
        //        pm => { pm.Length(30); pm.NotNullable(true); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Unit"),
        //        pm => { pm.Length(10); pm.NotNullable(true); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Password"),
        //        pm => { pm.NotNullable(true); });

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("State"),
        //        pm => pm.NotNullable(true));

        //    mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.Contains("Address"),
        //        pm => pm.Length(200));

        //}

        ///// <summary>
        ///// 实体属性约束映射
        ///// </summary>
        ///// <param name="mapper"></param>
        //private void EntityPropertyMapper(ref Mapper mapper)
        //{
        //    mapper.Class<Goods>(cm =>
        //    {
        //        cm.Property(q => q.Details, pm =>
        //        {
        //            pm.Length(int.MaxValue);
        //        });
        //    });

        //}
    }
View Code

    3,读取配置:

    这一步关键环节是调用Configuration对象的AddDeserializedMapping()方法添加HbmMapping和配置元数据。

 public static class NhConfig
    {
        private static readonly ISessionFactory _sessionFactory;
        private static Configuration _configuration;

        static NhConfig()
        {
            try
            {
                _configuration = new Configuration();
                var mapping = new MappingFactory().CreateMapping();
                _configuration.AddDeserializedMapping(mapping, null);
                var a = _configuration.Configure();
                _sessionFactory = a.BuildSessionFactory();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static Configuration Configuration
        {
            get { return _configuration; }
        }

        public static ISessionFactory SessionFactory
        {
            get { return _sessionFactory; }
        }
    }

    4,运行方法进行映射:

  

  public class MappingTestController : Controller
    {
        //
        // GET: /MappingTest/

        public ActionResult Index()
        {
            try
            {
                var update = new SchemaUpdate(NhConfig.Configuration);
                update.Execute(true, true);
            }
            catch (Exception)
            {

                throw;
            }


            return View();
        }

    }

配置文件web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

  </appSettings>
  <connectionStrings>
    <add name="connection_string" connectionString="Data Source=.;Initial Catalog=SCB;User ID=sa;Password=123123;" />
  </connectionStrings>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory name="NHibernate.Test">
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string_name">connection_string</property>
      <property name="adonet.batch_size">10</property>
      <property name="show_sql">false</property>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="command_timeout">60</property>
      <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    </session-factory>
  </hibernate-configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.3.1.4000" newVersion="3.2.0.4000" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.serviceModel>
    <bindings />
    <client />
  </system.serviceModel>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>
原文地址:https://www.cnblogs.com/tanzhen/p/5038641.html