zoukankan      html  css  js  c++  java
  • NHibernate 3.2: (part 2) mapping by code

    In the first post about the new mapping-by-code feature you saw only the very first presentation.

    I’ll will try to write more posts about this new feature and all its secrets even if you can learn more using ConfORM.

    As in ConfORM even the NHibernate’s mapping-by-code is smarter than XML mapping and may help you in many cases. Well… it is not so smart as ConfORM but smart enough to prevent some common errors.

    It’s beginner proof

    Let me show you a simple case:

    private class Person
    {
        public int Id { getset; }
        public ICollection<Address> Addresses { getset; }
    }

    private class Address
    {
        public Person Owner { getset; }
        public string Street { getset; }
        public Number Number { getset; }
    }

    private class Number
    {
        public Address OwnerAddress { getset; }
        public int Block { getset; }
    }

    An entity with a collection of components which has a nested component. The beginner may intent this mapping:

    mapper.Class<Person>(cm =>
    {
        cm.Id(x => x.Id);
        cm.Bag(x => x.Addresses, cp => { }, cr => cr.Component(ce =>
        {
            ce.ManyToOne(x => x.Owner);
            ce.Property(x => x.Street);
            ce.Component(x => x.Number, y =>
            {
                y.Component(x => x.OwnerAddress, map => { });
                y.Property(x => x.Block);
            });
        }));
    });

    hmmmm… a cyclic mapping of the nested component on OwnerAdress property ? Not for sure!! NHibernate knows how create the correct mapping Winking smile.

    It’s even conformist

    In these years I saw people writing mappings by-code but class-by-class as in XML… a very conformist attitude. Well… if you feel conformist don’t worry NHibernate 3.2 can be conformist too.

    public class MyClass
    {
        public virtual int Id { getset; }
        public virtual string Something { getset; }
    }

    public class MyClassMapClassMapping<MyClass>
    {
        public MyClassMap()
        {
            Id(x => x.Id, map =>
            {
                map.Column("MyClassId");
                map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
            });
            Property(x => x.Something, map => map.Length(150));
        }
    }

    Then you can add it to the ModelMapper in this way:

    mapper.AddMappings(typeof(AnyMappingClass).Assembly.GetTypes());

    NHibernate 3.2 too sexy by far!!!

  • 相关阅读:
    只使用代码创建WPF程序
    C#第一课
    VMware虚拟机的网络设置
    mac系统下配置Eclipse Java/C++ 开发环境
    【读书笔记】【物联网】《物物连起大世界物联网的应用与前景》
    移动硬盘无法格式化
    Win7下chm文件打不开的解决办法[转]
    MapInfo数据到ARCGIS数据Shapefile的转换
    mapx不具开发功能
    [读书笔记]熟悉SQLPLUS Oracle数据库环境
  • 原文地址:https://www.cnblogs.com/sunjie9606/p/2169729.html
Copyright © 2011-2022 走看看