第二篇:Entity Framework CodeFirst & Model 映射
前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现Mapping 又是怎样的呢? EntityFramework 实现Mapping 有两种方式。
1. 数据注解(DataAnnotations)
2. Fluent API
一. 数据注解,这种方式,就是在实体和属性加上一些EntityFramework 定义好的一些特性,然后EntityFramework,在具体操作数据库时进行反射。跟我们上篇提到 特性+反射 一样的方案。因此今天不会在这篇讲 DataAnnotations 。会贴一点实例代码。
比较要注意的是,实现 DataAnnotations ,要引用 System.ComponentModel.DataAnnotations 命名空间。

实例代码如下,特殊说明一下,EntityFramework 支持 .Net 可为空表达法,如 int?,DateTime? 。下面代码 最后修改时间 LastModifiedDateTime 就是这样。
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; namespace EntityFrameworkSample.Models
{
[Table("Sample_Order")] //标示为 表名
//[Table("Sample_Order", Schema = "dbo")] //标示为 表名 ,表的拥有者
public class OrderModel
{
[Key]//标示为 主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // 标示为 自动增量
public Guid OrderGuid { get; set; }
[Required] //标示为 必填
[MaxLength()] //标示为 字符串长度最大30
public string OrderNo { get; set; }
[Required] //标示为 必填
[MaxLength()] //标示为 字符串长度最大30
public string OrderCreator { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // 标示为 自动增量 数据库有默认值 getdate()
public DateTime OrderDateTime { get; set; }
[Required]
public string OrderStatus { get; set; }
[MaxLength()]
public string Description { get; set; }
[Required]
[MaxLength()] //标示为 字符串长度最大30
public string Creator { get; set; }
[Required]
public DateTime CreateDateTime { get; set; }
public string LastModifier { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
}
}
看吧,数据注解(DataAnnotations ),就是旧技术换一个叫法而已。没有什么大不了。其他的就靠大家去摸索了。
二 . Fluent API 查了一下百度翻译,“流畅的API” ,我不知道这个翻译贴不贴不切,我就以我使用Fluent API 经验说说,Fluent API 比 数据注解好的地方。
1. 大家再看一眼上面代码,是不是感觉有点不纯净了,本来一个干干净净的类,搞得乱乱的。感觉有点恶心。
2. 这一点可能要后面我贴出代码,分享源代码才理解,不过使用过EntityFramework Fluent API 的应该能够理解到,配置和类分离,职责更加单一。
3. 配置和类分离,扩展性,灵活性就会更好,大家多知道,EntityFramework 不仅支持Sql Server,支持Oracle,MySql,Sqlite 等这些流行数据库,每种产品配置也许都有细微差别,如果以 DataAnnotations 方式实作,那我岂不是要重新新增模型,一样的表设计,为什么要加呢? 只有配置不同才要加啊!
4. 做技术架构,这种方式封装也比较好,怎么好大家如果是做架构的话,两种方式都用一下,感受一下。
废话不多说了,直接贴出实现 Fluent API 的流程,以及代码。
1. 创建数据库“EntityFrameworkSample”
2. 在数据库“EntityFrameworkSample”中,加表“Sample_Order”,然后向表中新增所需要的字段。

3. 新建解决方案 “EntityFrameworkSample”
4. 在解决方案中 新增“EntityFrameworkSample.DbContext” (配置最终使用地方),“EntityFrameworkSample.Models”(纯净数据Model),“EntityFrameworkSample.Mappings” (映射配置)三个类库项目
5. 在“EntityFrameworkSample.DbContext” ,“EntityFrameworkSample.Mappings” 项目中,通过NuGet 安装EntityFramework 最新版本。

6. 在 “EntityFrameworkSample.DbContext” 项目中,新增“EntityFrameworkSampleDbContext” DbContext 类,
在“EntityFrameworkSample.Models” 项目中,新增“OrderModel” Model类,
在“EntityFrameworkSample.Mappings”项目中,新增“OrderMap” 映射配置类。
三个项目 代码图 和引用关系如下图

三个类的代码分别如下
EntityFrameworkSampleDbContextusing System.Data.Entity;using EntityFrameworkSample.Mappings;
using EntityFrameworkSample.Models; namespace EntityFrameworkSample.DbContext
{
public class EntityFrameworkSampleDbContext:System.Data.Entity.DbContext
{
public EntityFrameworkSampleDbContext()
: base("EntityFrameworkSampleConnection")
{
} public DbSet<OrderModel> orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ modelBuilder.Configurations.Add(new OrderMap()); base.OnModelCreating(modelBuilder);
}
}
}
OrderModel
using System; namespace EntityFrameworkSample.Models
{
public class OrderModel
{
public Guid OrderGuid { get; set; }
public string OrderNo { get; set; }
public string OrderCreator { get; set; }
public DateTime OrderDateTime { get; set; }
public string OrderStatus { get; set; }
public string Description { get; set; }
public string Creator { get; set; }
public DateTime CreateDateTime { get; set; }
public string LastModifier { get; set; }
public DateTime LastModifiedDateTime { get; set; }
}
}
OrderMap
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using EntityFrameworkSample.Models; namespace EntityFrameworkSample.Mappings
{
public class OrderMap : EntityTypeConfiguration<OrderModel>
{
public OrderMap()
{
this.HasKey(m => m.OrderGuid); this.Property(m => m.OrderGuid)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(m => m.OrderNo)
.IsRequired()
.HasMaxLength(); this.Property(m => m.OrderCreator)
.IsRequired()
.HasMaxLength(); this.Property(m => m.OrderStatus)
.IsRequired()
.HasMaxLength(); this.Property(m => m.Description)
.HasMaxLength(); this.Property(m => m.Creator)
.IsRequired()
.HasMaxLength(); this.Property(m => m.LastModifier)
.HasMaxLength()
.HasMaxLength(); this.ToTable("Sample_Order"); this.Property(m => m.OrderGuid).HasColumnName("OrderGuid");
this.Property(m => m.OrderNo).HasColumnName("OrderNo");
this.Property(m => m.OrderCreator).HasColumnName("OrderCreator");
this.Property(m => m.OrderDateTime).HasColumnName("OrderDateTime");
this.Property(m => m.OrderStatus).HasColumnName("OrderStatus");
this.Property(m => m.Description).HasColumnName("Description");
this.Property(m => m.Creator).HasColumnName("Creator");
this.Property(m => m.CreateDateTime).HasColumnName("CreateDateTime");
this.Property(m => m.LastModifier).HasColumnName("LastModifier");
this.Property(m => m.LastModifiedDateTime).HasColumnName("LastModifiedDateTime");
}
}
}
至此解决方案此阶段所有代码就完成了。

大概讲一下一些注意点。
1. EntityFrameworkSampleDbContext 必须要继承 DbContext,并重写OnModelCreating方法,来完成映射.
2. OrderMap 必须继承EntityTypeConfiguration<>泛型类,泛型类型 OrderModel,大概告诉Map映射的是OrderModel。
好了,这篇内容结束了,不足的地方,我没有列出Fluent API 所有api,主要是表与表的关系是如何映射的,这些希望读者,能够自己去摸索,篇幅有限,
还有就是DbContext 我也没有在这篇详细介绍,会在真正讲到DbContext那篇在详细跟大家介绍。
这篇还增加一篇续篇吧,第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
这篇的源代码:http://pan.baidu.com/s/1gftuzuF
第二篇:Entity Framework CodeFirst & Model 映射的更多相关文章
- 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...
- 第二篇 Entity Framework Plus 之 Query Future
从性能的角度出发,能够减少 增,删,改,查,跟数据库打交道次数,肯定是对性能会有所提升的(这里单纯是数据库部分). 今天主要怎样减少Entity Framework查询跟数据库打交道的次数,来提高查询 ...
- 第三篇 Entity Framework Plus 之 Query Cache
离上一篇博客,快一周,工作太忙,只能利用休息日来写一些跟大家分享,Entity Framework Plus 组件系列文章,之前已经写过两篇 第一篇 Entity Framework Plus 之 A ...
- Entity Framework CodeFirst数据迁移
前言 紧接着前面一篇博文Entity Framework CodeFirst尝试. 我们知道无论是“Database First”还是“Model First”当模型发生改变了都可以通过Visual ...
- entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败
警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...
- Entity Framework Code-First(20):Migration
Migration in Code-First: Entity framework Code-First had different database initialization strategie ...
- How to: Supply Initial Data for the Entity Framework Data Model 如何:为EF数据模型提供初始数据
After you have introduced a data model, you may need to have the application populate the database w ...
- ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)
ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...
- Entity Framework : The model backing the '' context has changed since the database was created
1.采用code first 做项目时,数据库已经生成,后期修改数据库表结构.再次运行时出现一下问题: Entity Framework : The model backing the '' cont ...
随机推荐
- Lesson 10 Not for jazz
Text We have an old musical instrument. It is called a clavichord. It was made in Germany in 1681. O ...
- AnguarJS 第二天----数据绑定
Terms 今天学习AngularJS双向数据绑定的特性,这里面需要提到两个概念: 数据模型:数据模型是指 $scope对象, $scope对象是简单的javascript对象,视图可以访问其中的属性 ...
- HappyAA服务器部署笔记2(nginx的静态资源缓存配置)
我近期对服务器进行了少量改进,虽然之前使用了nginx反向代理之后性能有所提高,但仍然不够,需要使用缓存来大幅度提高静态资源的访问速度. 服务器上的静态资源主要有这些:png, jpg, svg, j ...
- GIS规划应用——基于哈夫模型的GIS服务区分析
1. GIS服务区分析 区位因素是商业分析中一个至关重要的因素,因此在商店选址时,例行的服务区分析十分重要.服务区是指顾客分布的主要区域,在其范围内该店的商品销售量或服务营业额超过其竞争对手.对于现 ...
- Git Shell 基本命令(官网脱水版)
用户信息 当安装完 Git 应该做的第一件事就是设置你的用户名称与邮件地址. 这样做很重要,因为每一个 Git 的提交都会使用这些信息,并且它会写入到你的每一次提交中,不可更改: $ git conf ...
- HTTP学习一:HTTP基础知识
1 HTTP介绍 HTTP协议(HyperText Transfer Protocol,超文本传输协议)是用于从WWW服务器传输超文本到本地浏览器的传送协议. 它的发展是万维网协会(World Wid ...
- EasyUI刚加载时候Window窗体自动弹出的解决办法
- 网站初步收工---www.dkill.net
今天10.30左右备案核审成功了,然后一天都在忙部署和一些其他的东西,中途也写了很多文档,遇到很多问题,直接琢磨了N久,暂时发了这么多教程,明天揭露阿里云的各种坑(先用winServer服务器,有时间 ...
- A Simple OpenCASCADE Qt Demo-occQt
A Simple OpenCASCADE Qt Demo-occQt eryar@163.com Abstract. OpenCASCADE have provided the Qt samples ...
- 如何部署Icinga服务端
Icinga是Nagios的一个变种,配置,使用方式几乎一样,而且完全兼容Nagios的插件.所以下面的部署方案对Nagios同样使用. 它还推出了两个中文版本,icinga-cn原版和icinga- ...