什么是 NHibernate.Mapping.Attributes?
NHibernate.Mapping.Attributes 是 NHibernate 的附加软件,它是Pierre Henri Kuat (aka KPixel)贡献的; 以前的实现者是 John Morris.NHibernate需要映射信息来绑定你的域对象到数据库。通常他们被写在(并且被保存在)在分散的hbm.xml文件里。
使用NHibernate.Mapping.Attributes,你可以使用.NET属性(attributes)来修饰你的实体和被用于产生.hbm.xml映射(文件或者流)的属性(attributes)。因此,你将不再会为这些令人厌恶的文件而烦恼。
这个库里面的内容包括。
-
NHibernate.Mapping.Attributes: 你需要的唯一工程(作为最终用户)
-
Test:一个使用属性(attributes)和HbmSerializer的简单用例,是NUnit的TestFixture
-
Generator: 用来产生属性(attributes) 和HbmWriter的程序.
-
Refly : 感谢Jonathan de Halleux 提供这个库,它使得产生代码变得如此简单.
重要提示
这个库是使用文件/src/NHibernate.Mapping.Attributes/nhibernate-mapping-2.0.xsd(它嵌入在程序集中能够检查产生的XML流的合法性)产生的.这个文件可能在NHibernate每次发布新版本时发生变化,所以你应该在不同的版本中使用它时,重新生成它(打开Generator工程,编译并且运行Generator项目).但是,在0.8之前的版本中它并没有通过测试.
最终用户类 是NHibernate.Mapping.Attributes.HbmSerializer.这个类序列化你的域模型到映射流.你可以逐个序列化程序集中的类.NHibernate.Mapping.Attributes.Test可以作为参考.
第一步用属性(attributes)修饰你的实体;你可以用 [Class], [Subclass], [JoinedSubclass]或者[Component].然后,修饰成员(字段/属性properties);它们能够代替很多映射中需要使用的属性(attributes ),例如:
[NHibernate.Mapping.Attributes.Class]
public class Example

...{
[NHibernate.Mapping.Attributes.Property]
public string Name;
}
完成这个步骤后,使用NHibernate.Mapping.Attributes.HbmSerializer:(这里我们使用了Default ,它是一个实例,在你不必须/不想自己创建它时使用).
System.IO.MemoryStream stream = new System.IO.MemoryStream(); // where the xml will be written
NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (可选)
// Here, we serialize all decorated classes (but you can also do it class by class)
NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(
stream, System.Reflection.Assembly.GetExecutingAssembly() );
stream.Position = 0; // Rewind
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.Configure();
cfg.AddInputStream(stream); // Use the stream here
stream.Close();
// Now you can use this configuration to build your SessionFactory...
注意
正如你所见:
NHibernate.Mapping.Attributes是没有(真正的)侵入性的.在你的对象上设置属性(attributes ),不会强迫你在NHibernate 使用它们,并且不会破坏你的架构体系中的任何约束.属性(Attributes)仅仅是纯粹的信息.
-
使用HbmSerializer.Validate来启用/禁用产生的xml流的合法性检查(依靠NHibernate mapping schema);对于快速查找问题这是很有用的(它们被StringBuilder写入HbmSerializer.Error).如果错误是这个库预期的,库会看它是否是已知的问题并且报告它;解决这些问题能帮助你完成你的解决方案. :)
-
你的类,字段和属性properties(成员)可以是私有的;请确认你有使用反射访问私有成员的权限(ReflectionPermissionFlag.MemberAccess).
-
映射类的成员也会在基类中查找(直到找到映射的基类).因此,你可以在基类(没有做映射)中修饰成员,然后在它的(做过映射的)子类中使用它.