• NHibernate ConfORM Mapping


    前言

      昨天写了一篇fluent nhibernate通过约定的代码映射方式,NH在3.0版本以后已经集成了conform的代码映射方式,一直没注意也没使用过,今天试试怎么样。

    步骤

    1、通过conform方式生成如下数据库架构

    2、添加项目对NH3.3的引用,3.0以后已经集成代码映射的方式在using NHibernate.Mapping.ByCode.Conformist;using NHibernate.Mapping.ByCode;命名空间中。

    编写持久化对象:

    public class Province
        {
            public Province()
            {
                Cities = new List<City>();
            }
            virtual public int Name{get;set;}
    
            virtual public int ProvienceID{get;set;}
    
            virtual public IList<City> Cities { get; set; }
        }
    public class City
        {
            virtual public int CityID{get;set;}
    
            virtual public int Name{get;set;}
    
            virtual public Province Province { get; set; }
        }

    集成using NHibernate.Mapping.ByCode.Impl.CustomizersImpl;命名空间下的ClassMapping<T>来实现代码配置持久化对象映射

    Provience映射代码:

    public class ProvinceMap : ClassMapping<Province>
        {
            public ProvinceMap()
            {
                Id(p => p.ProvienceID, map => map.Generator(Generators.Assigned));
    
                Property(p => p.Name);
    
                Bag(p => p.Cities, map => map.Key(k => k.Column("ProvinceId")), ce => ce.OneToMany());
            }
        }

    CIty类映射代码:

    public class CityMap : ClassMapping<City>
        {
            public CityMap()
            {
                Id(p => p.CityID, map => map.Generator(Generators.Assigned));
                Property(p => p.Name);
                ManyToOne(p => p.Province, map => map.Column("ProvinceId"));
            }
        }

    3、NH配置

    首先我们添加一个数据库连接的配置文件:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="NHConform" connectionString="Data Source=(local);initial catalog=NHConform;Integrated Security=SSPI"/>    
      </connectionStrings>
    </configuration>

    编写一个配置NH的类:

    public static class NHContext
        {
            public static Configuration NHConfiguration { get; set; }
            public static ISessionFactory SessionFactory { get; set; }
    
            public static void AppConfigure()
            {
                #region NHibernate配置
    
                NHConfiguration = ConfigureNHibernate();
    
                SessionFactory = NHConfiguration.BuildSessionFactory();
    
                #endregion
            }
    
            private static Configuration ConfigureNHibernate()
            {
                var configure = new Configuration();
                configure.SessionFactoryName("BuildIt");
    
                configure.DataBaseIntegration(db =>
                {
                    //配置数据库连接
                    db.Dialect<MsSql2008Dialect>();
                    db.Driver<SqlClientDriver>();
                    db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                    db.IsolationLevel = IsolationLevel.ReadCommitted;
    
                    db.ConnectionStringName = "NHConform";
                    db.Timeout = 10;
    
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = true;
                    db.AutoCommentSql = true;
                });
    
                var mapping = GetMappings();
                //在Configuration中添加HbmMapping
                configure.AddDeserializedMapping(mapping, "NHConfORM");
                //配置元数据
                SchemaMetadataUpdater.QuoteTableAndColumns(configure);
    
                return configure;
            }
    
            public static HbmMapping GetMappings()
            {
                var mapper = new ModelMapper();
    
                mapper.AddMappings(Assembly.GetAssembly(typeof(ProvinceMap)).GetExportedTypes());
                var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
    
                return mapping;
            }
        }

    4、测试映射配置生成数据库架构,建了一个控制台程序没有写单元测试,生成数据库架构的代码

    public static void Create()
            {
                NHContext.AppConfigure();
                new SchemaExport(NHContext.NHConfiguration).Create(false, true);
            }

    在控制台主程序中执行Create()方法,生成数据库并生成如上图的数据库关系图。

    测试删除数据库:

    public static void Drop()
            {
                NHContext.AppConfigure();
                new SchemaExport(NHContext.NHConfiguration).Drop(false, true);
            }

    执行Drop()方法以后数据库结构就被删除了,此处就不截图了。

    结语

      NH自带的代码映射方式同样支持编写规则映射,这样在项目中会节约很多的时间,相比直接感觉还是用这个比较直接了,毕竟不需要引入第三方类库。

    此映射方式初次使用,若有不合理的地方,欢迎批评指正。

  • 相关阅读:
    Leetcode: N-Queens
    Leetcode: Sudoku Solver
    Leetcode: Binary Tree Maximum Path Sum
    Leetcode: Gas Station
    Leetcode: Convert Sorted List to Binary Search Tree
    Leetcode: Permutations II
    Leetcode: Reorder List && Summary: Reverse a LinkedList
    Leetcode: Unique Binary Search Trees II
    Leetcode: Subsets II
    Leetcode: Unique Paths II
  • 原文地址:https://www.cnblogs.com/flykai/p/3270569.html
Copyright © 2020-2023  润新知