Nhibernate 映射 FluentApi Mapping by Code
2015-06-06 16:18
447 查看
Nhibernate 映射 FluentApi Mapping by Code
nHibernate 3.2新增了一种mapping by code的映射策略,很有意思。你可以自定义约定,并且按照约定定制自动映射策略, 面对遗留数据库时这个功能往往很有用,另外,由于mapping by code是基于代码的(而不是xml文件), 对domain object进行重命名的重构操作会非常方便,不用跑到xml映射文件查找字符串了。代码
//实体类 public class User { public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IList<Article> Articles { get; set; } } public class UserProfile { public virtual long Id { get; set; } public virtual Gender Gender { get; set; } public virtual DateTime? Birthday { get; set; } public virtual string Email { get; set; } } public class Article { public virtual long Id { get; set; } public virtual string Content { get; set; } public virtual User User { get; set; } } //ORM映射 public class UserMapping : ClassMapping<User> { public UserMapping() { //对应的数据库表名 Table("User"); //定义读写属性 Cache(map => map.Usage(CacheUsage.ReadWrite)); //定义主键是自增的 Id(t => t.Id, map => map.Generator(Generators.Native)); //普通属性 Property(t => t.Name); //定义一对一映射 OneToOne(t => t.UserProfile, map => map.Cascade(Cascade.All)); //映射的文章列表 删除User时会级联删除对应的文章 Bag(t => t.Articles , map => { map.Key(k => k.Column("ArticleId")); map.Inverse(true); map.Cascade(Cascade.Remove); }, rel => rel.OneToMany()); } } public UserProfileMapping() { Table("UserProfile"); Cache(map => map.Usage(CacheUsage.ReadWrite)); Id(t => t.Id, map => map.Generator(Generators.Foreign<UserProfile>(p => p.User))); Property(t => t.Birthday); Property(t => t.Email); OneToOne(t => t.User, map => map.Constrained(true)); } public class ArticleMapping : ClassMapping<Article> { public ArticleMapping() { Table("Article"); Cache(map => map.Usage(CacheUsage.ReadWrite)); Id(t => t.Id, map => map.Generator(Generators.Native)); Property(t => t.Content); //定义多对一关系 多个Article对应一个User //对应数据库列名 ManyToOne(t => t.User, map => { map.Column("UserId"); }); } }
参考过这里,好文啊
相关文章推荐
- hibernate执行原生sql语句问题
- spring.net配置错误:Could not load type from string value ...
- Database
- Database
- 用Demo記錄knockoutjs之mapping擴展的使用
- 此 SqlParameterCollection 的 Count=4 的索引 4 无效。
- NHibernate学习之-配置
- hibernate.MappingException: entity class not found
- org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
- 使用MyBatis_Generator生成Dto、Dao、Mapping
- Spring.net实战开发教程下载 Spring.net视频教程
- 解决HibernateException: Illegal attempt to associate a collection with two open sessions
- Hibernate Mapping Declaration——之 一
- NHibernate使用之详细图解
- OpenGLES demo - 12. 材质贴图 Texture Mapping
- ETL -- SDE AND SIL
- web.xml的配置
- 关于NHibernate实体和hbm.xml的那些错误
- NHibernate 错误原因:Invalid Cast (check your mapping for property type mismatches)
- 大家一起来学 NHibernate+NUnit (VS2012+SQL Server2008)