NHibernate初学者指南(6):映射模型到数据库之方式二

使用Fluent NHibernate自动映射

使用Fluent NHibernate自动映射,首先要将映射的实体放到一个命名空间中,这使得通知AutoMapper哪些实体和值对象包含在映射中更容易。建议在你的项目中创建一个Domain文件夹,将需要映射的实体和值对象放到这个文件夹中。

因为隐式映射实体和值对象,需要为AutoMapping定义约定和例外。我们通过实现一个继承自DefaultAutomappingConfiguration的配置类实现。

假设我们已经将所有的实体和值对象放在了相同的命名空间中,这个命名空间只包含domain类,我们就可以如下面的代码定义配置类:

public class OrderingSystemConfiguration : DefaultAutomappingConfiguration
{public override bool ShouldMap(Type type){return type.Namespace == typeof(Customer).Namespace;}
}

上面的代码告诉AutoMapping只映射那些和Customer实体有相同命名空间的类。

在AutoMapper工作之前,我们还需要告诉它更多的事情。我们必须告诉它在系统中谁是值对象。这可以在配置类中重写IsComponent方法实现,如下面代码所示:

public override bool IsComponent(Type type)
{var componentTypes = new[] { typeof(Name), typeof(Address) };return componentTypes.Contains(type);
}

配置系统使用自动映射,我们利用下面的代码:

var cfg = new OrderingSystemConfiguration();
var configuration = Fluently.Configure().Database(/* database config */).Mappings(m =>m.AutoMappings.Add(AutoMap.AssemblyOf<Employee>(cfg))).BuildConfiguration();

 

实战时间–使用自动映射

在这个例子中,我们想定义一个基本的领域模型,使用Fluent NHibernate提供的自动映射来映射我们的模型,然后让NHibernate根据映射为我们生成数据库架构:

1. 在VS中创建一个Console Application,名字为:AutoMappingSample。

2. 添加NHibernate.dll和FluentNHibernate两个程序集到项目中。

3. 在项目中新建一个Domain文件夹。

4. 分别添加以下类到Domain文件夹中:

Customer类

namespace AutoMappingSample.Domain
{public class Customer{public virtual int Id { get; set; }public virtual string CustomerName { get; set; }}
}

LineItem类

namespace AutoMappingSample.Domain
{public class LineItem{public virtual int  Id { get; set; }public virtual int  Quantity { get; set; }public virtual decimal UnitPrice { get; set; }public virtual string ProductCode { get; set; }}
}

Order类

namespace AutoMappingSample.Domain
{public class Order{public virtual int Id { get; set; }public virtual DateTime OrderDate { get; set; }public virtual Customer Customer { get; set; }public virtual IList<LineItem> LineItems { get; set; }}
}

5. 在项目中添加一个OrderingSystemConfiguration类,继承自DefaultAutomappingConfiguration。

6. 重写ShouldMap方法,如下面的代码:

namespace AutoMappingSample
{public class OrderingSystemConfiguration : DefaultAutomappingConfiguration{public override bool ShouldMap(Type type){return type.Namespace == typeof(Customer).Namespace;}}
}

7. 在Program类中添加如下using语句:

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using AutoMappingSample.Domain;
using NHibernate.Tool.hbm2ddl;

8. 添加下面的代码到Program类的Main方法创建NHibernate配置。配置对象使用Fluent NHibernate的配置API创建用于自动映射。

var cfg = new OrderingSystemConfiguration();
var configuration = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008).Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Customer>(cfg))).BuildConfiguration();

注意为这个操作定义数据库字符串没有必要,因为我们不访问数据库,只是告诉NHibernate哪种类型的数据库。

9. 添加下面的代码创建并在控制台上显示SQL脚本:

var exporter = new SchemaExport(configuration);
exporter.Execute(true, false, false);

10. 添加下面的代码避免程序不经确认就退出:

Console.WriteLine("按回车退出:");
Console.ReadLine();

11. 运行程序,控制台输出如下:

automapping

使用ConfORM自动映射

ConfORM是NHibernate contributions的一部分,可从http://code.google.com/p/codeconform/downloads/list下载。确保下载的版本兼容你使用的NHibernate版本。

和Fluent NHibernate的AutoMapper一样,ConfORM使用约定隐式定义领域模型的映射。这些约定可以重写,也可以定义我们自己的约定。

实战时间–使用ConfORM映射模型

在这个例子中,我们再一次创建一个简单的领域模型并使用ConfORM为我们创建一个隐式的映射。然后我们使用NHiernate的schema exporter创建SQL脚本来创建兼容我们模型的数据库架构。

1. 打开VS,创建一个Console Application项目,名字为:ConfORMSample。

2. 添加对NHibernate.dll和ConfORM.dll程序集的引用到项目中。我使用的NHibernate版本是3.1的,所以ConfORM也是兼容3.1的ConfORM 1.0.1.5。

3. 在项目中创建一个Domain文件夹。

4. 添加上一个例子中的Customer,Order和LineItem类到Domain文件夹。

Customer类

namespace ConfORMSample.Domain
{public class Customer{public virtual int Id { get; set; }public virtual string CustomerName { get; set; }}
}

Order类

namespace ConfORMSample.Domain
{public class Order{public virtual int Id { get; set; }public virtual DateTime OrderDate { get; set; }public virtual Customer Customer { get; set; }public virtual IList<LineItem> LineItems { get; set; }}
}

LineItem类

namespace ConfORMSample.Domain
{public class LineItem{public virtual int  Id { get; set; }public virtual int  Quantity { get; set; }public virtual decimal UnitPrice { get; set; }public virtual string ProductCode { get; set; }}
}

5. 在Program类中添加如下using语句:

using ConfORMSample.Domain;
using ConfOrm;
using ConfOrm.NH;
using NHibernate.Cfg;
using NHibernate.Cfg.Loquacious;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;

6. 在Program类的Main方法中,使用NHibernate提供的fluent配置API创建一个NHibernate配置对象:

var configuration = new Configuration();
configuration.DataBaseIntegration(db =>
{db.Dialect<MsSql2008Dialect>();db.Driver<SqlClientDriver>();
});

7. 添加如下代码,确定要映射的类型:

var types = typeof(Customer).Assembly.GetTypes().Where(t => t.Namespace == typeof(Customer).Namespace);

8. 创建一个类型为ObjectRelationalMapper的实例,如下面的代码所示:

var orm = new ObjectRelationalMapper();

9. 告诉映射器,应该为每一个类型创建一个表,如下所示:

orm.TablePerClass(types);

10. 创建映射,并将它们添加到配置对象,如下面的代码所示:

var mapper = new Mapper(orm);
var hbmMappings = mapper.CompileMappingFor(types);
configuration.AddDeserializedMapping(hbmMappings, "MyDomain");

11. 创建schema生成脚本,如下面的代码所示:

var exporter = new SchemaExport(configuration);
exporter.Execute(true, false, false);

12. 同样,添加下面的代码为避免程序未经确认就退出:

Console.Write("按回车退出:");
Console.ReadLine();

13. 运行程序,如下图所示:

ConfORM

没用编码和少量的配置,我们就使系统为我们的领域模型创建了一个隐式的映射,并导出为可以创建数据库架构的脚本。生成的脚本基于定义在ConfORM中的约定。所有的这些约定都可以重写,也可以根据需要添加自己的约定。

自动映射到此为止,下一篇介绍XML映射。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/404698.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

解决升级mac os X EI Capitan后遇到LibclangError: dlopen(libclang.dylib, 6): image not found.的问题...

打开文件./frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py 把第 3395 行 改为 &#xff1a; library cdll.LoadLibrary("../bindings-generator/libclang/" self.get_filename())转载于:https://www.cnblogs.com/HemJohn/p/4978859.html

[react] 高阶组件(HOC)有哪些优点和缺点?

[react] 高阶组件(HOC)有哪些优点和缺点&#xff1f; HOC 优点 通过传递props去影响内层组件的状态&#xff0c;不直接改变内层组件的状态&#xff0c;降低了耦合度 缺点 组件多层嵌套&#xff0c; 增加复杂度与理解成本 ref隔断&#xff0c; React.forwardRef 来解决 高阶组件…

STM32嵌入式系统FreeRTOS使用cJSON解析和构建JSON

一、环境 控制器STM32F407MDK5.34cJSON1.7.7 二、安装cJSON MDK中打开Pack Install&#xff0c;选择Generic下边MDK-Pack::cJSON&#xff0c;点击安装Install 安装成功后&#xff0c;在Manage Run-Time Environment 中找到Data Exchange&#xff0c;并选择cJSON&#xff0c;…

objectC 数据类型转换

按照数据类型占用存储不同可以自动类型转换或强制类型转换&#xff0c;总的原则是小存储容量数据类型可以自动转换成为大存储容量数据类型。 不同类型数据间按照下面关系的从左到右&#xff08;从低到高&#xff09;自动转换&#xff0c; _Bool、char、short int、枚举类型 -&g…

VC6启用运行时类型识别 (RTTI)

在程序中&#xff0c;当我们对多态类的基类指针使用typeid&#xff0c;就可以在运行时确定指针指向对象的实际类型&#xff0c;并输出对象类型的名字。 #include <cstdlib >#include <iostream >#include <typeinfo >usingnamespacestd; classB{ public …

爱快软路由设置DHCP多个LAN处于同一网段

&#xff08;0&#xff09;思路&#xff1a;eth0 启用扩展网卡&#xff0c;然后设置LAN1为DHCP。 &#xff08;1&#xff09;设置扩展网卡 &#xff08;2&#xff09;启用DHCP

[react] react16跟之前的版本生命周期有哪些变化?

[react] react16跟之前的版本生命周期有哪些变化&#xff1f; 个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题

前端招聘与前端卖身的困境

最近开始物色新公司&#xff0c;群里来了个招人的&#xff0c;说2.5万招高手。在众人的怂恿下&#xff0c;发了简历。 但结果是不如意的&#xff0c;经过他们一小时的评测&#xff0c;他们认为我的水平不过8k-10k&#xff0c;税前。我吐血了&#xff0c;还远低于我原来的呢&…

git 本地推送本地仓库到远程

github或者gitee远程新建空仓库&#xff0c;在本地推送已有的仓库到远程新仓库。 1、远程新建新仓库&#xff0c;例如stm32repo 2、本地仓库添加远程仓库 git remote add origin https://gitee.com/xxxx/stm32repo.git 3、本地仓库完成提交后&#xff0c;推送到远程仓库 gi…

无法对视图创建索引,因为该视图未绑定到架构

遇到这个问题&#xff0c;查了一位博主的文章&#xff0c;但是说的不是很详细&#xff0c;在这里说明白一些。 修改此问题 需要在 创建视图语句中加上 with SCHEMABINDING --创建索引视图 create view 视图名 with schemabinding as select 语句 go --创建索引视图需要注意的几…

[react] react怎么提高列表渲染的性能?

[react] react怎么提高列表渲染的性能&#xff1f; 使用webpack 做代码分割。使用hooks。个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题

Windows编程中的映射模式和坐标转换

From: http://www.vczx.com/article/show.php?id1011820 一、Windows中的映射模式 1、Windows定义映射模式的目的 经过我的综合&#xff0c;Windows定义映射模的目的又以下几个方面&#xff1a;1、不同人的使用习惯。不同国家的&#xff0c;不同地区&#xff0c;以及不同的人…

C# 截取图片的方法

1、C#截取图片的方法 方法一、 一个像素一个像素的画&#xff0c;遍历每一个像素&#xff0c;速度慢 /// <summary> /// 截取一张图片的制定部分 /// </summary> /// <param name"bitmapPathAndName">原始图片路径名称<…

变压器油参数

以下体胀系数参考百度百科&#xff1a; 水银1.8210^-4 纯水2.0810^-4 煤油9.010^-4 酒精1.110^-3 汽油1.2410^-3 氢气3.6610^-3 氧气3.6710^-3 氨气3.8010^-3 空气 3.67610^-3 二氧化碳3.74110^-3 一切气体 ≈1/273 甘油 4.910^-4 乙醇 7.510^-4 相关&#xff1a…

Python用过的小知识备忘录

1. python中的优先权队列&#xff0c;priorityqueue用法&#xff1a;数字越小&#xff0c;表示优先级越高&#xff0c;越早被拿出 from queue import Queue from queue import PriorityQueue prioqueuePriorityQueue() prioqueue.put((1,hahaha)) prioqueue.put((5,ustc)) pr…

[react] 给组件设置很多属性时不想一个个去设置有什么办法可以解决这问题呢?

[react] 给组件设置很多属性时不想一个个去设置有什么办法可以解决这问题呢&#xff1f; es6展开运算符 个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题

cygwin This indicates that the /etc/passwd (and possibly /etc/group) files should be rebuilt 问题解决办法

From: http://blog.csdn.net/deaboway/article/details/6461587 我的Cygwin报&#xff1a; [css] view plaincopyYour group is currently "mkpasswd". This indicates that the /etc/passwd (and possibly /etc/group) files should be rebuilt. See the man p…

CSS布局教程:用DIV CSS实现国内经典式三行两列布局-CSS布局实例

我们碰到过很多的企业网站或其它小型的展示类网站&#xff0c;有一些共同的特点&#xff0c;即顶部放一个大的导航或BANNER&#xff0c;右侧是链接或图片&#xff0c;左侧放置内容&#xff0c;页面底部放置版权信息等。这样的形式是国内经典式的布局&#xff0c;我们这里不对它…

EC20模组使用MQTT库对接EMQX,基于STM32F407

一、说明 本lib库基于STM32F407编译&#xff0c;其他的cortexM4内核也支持&#xff0c;采用串口和EC20模组通信。 库包括两个文件&#xff1a;ec20_mqtt.h和ec20_mqtt.lib。使用时添加lib文件到工程中&#xff0c;头文件引用ec20_mqtt.h即可。 下载&#xff1a;https://gitee…

[react] 说说react diff的原理是什么

[react] 说说react diff的原理是什么 内存中存储两颗树&#xff0c;一颗树是已经渲染的树结构&#xff08;Current Tree&#xff09;&#xff0c;另一颗是即将变化的树&#xff08;Fiber Tree&#xff09;。 每次状态发生变化&#xff0c;会对原来的树结构进行遍历&#xff0c…