前一篇 第一篇: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 映射的更多相关文章

  1. 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用

    上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...

  2. 第二篇 Entity Framework Plus 之 Query Future

    从性能的角度出发,能够减少 增,删,改,查,跟数据库打交道次数,肯定是对性能会有所提升的(这里单纯是数据库部分). 今天主要怎样减少Entity Framework查询跟数据库打交道的次数,来提高查询 ...

  3. 第三篇 Entity Framework Plus 之 Query Cache

    离上一篇博客,快一周,工作太忙,只能利用休息日来写一些跟大家分享,Entity Framework Plus 组件系列文章,之前已经写过两篇 第一篇 Entity Framework Plus 之 A ...

  4. Entity Framework CodeFirst数据迁移

    前言 紧接着前面一篇博文Entity Framework CodeFirst尝试. 我们知道无论是“Database First”还是“Model First”当模型发生改变了都可以通过Visual ...

  5. entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败

    警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...

  6. Entity Framework Code-First(20):Migration

    Migration in Code-First: Entity framework Code-First had different database initialization strategie ...

  7. 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 ...

  8. ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)

    ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...

  9. Entity Framework : The model backing the '' context has changed since the database was created

    1.采用code first 做项目时,数据库已经生成,后期修改数据库表结构.再次运行时出现一下问题: Entity Framework : The model backing the '' cont ...

随机推荐

  1. 【数据结构】平衡二叉树—AVL树

    (百度百科)在计算机科学中,AVL树是最先发明的自平衡二叉查找树.在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树.查找.插入和删除在平均和最坏情况下都是O(log n).增 ...

  2. Hadoop学习笔记—12.MapReduce中的常见算法

    一.MapReduce中有哪些常见算法 (1)经典之王:单词计数 这个是MapReduce的经典案例,经典的不能再经典了! (2)数据去重 "数据去重"主要是为了掌握和利用并行化思 ...

  3. 利用Hexo搭建个人博客-环境搭建篇

    我是一个爱写博客进行总结分享的人.然而,有着热爱写博客并且深知写博客好处的我,却没有好好的把这个习惯坚持下来.如今毕业已经一年多了吧,每一次与师弟师妹们聊天,我总会意味深长的建议他们,一定要定期梳理总 ...

  4. 说说Java程序和数据库交互的乱码解决

    本文就本人遇到的问题进行讲解 1.通过jdbc直连方式,连接Mysql数据库,从程序向数据库中写入数据出现的乱码解决方案. 当通过程序向Student表中写入一条数据时,写入数据库的内容会产生乱码. ...

  5. TODO:小程序集成WeUI

    TODO:小程序集成WeUI WeUI 为微信 Web 服务量身设计.WeUI 是一套同微信原生视觉体验一致的基础样式库,由微信官方设计团队为微信 Web 开发量身设计,可以令用户的使用感知更加统一. ...

  6. iOS-UI-UI控件概述

    以下列举一些在开发中可能用得上的UI控件: IBAction和IBOutlet,UIView 1 @interface ViewController : UIViewController 2 3 @p ...

  7. python django基础(二)

    django MTV模式之----template模版 django是动态的网页,后台的数据需要动态的插入到前端中,这时就依赖于django的template模版框架.django支持多种模版框架,下 ...

  8. 收集的React.JS资料

    主页 http://facebook.github.io/react/ https://github.com/facebook/react   中文站 http://www.reactjs.cn/ h ...

  9. Codeforces Round #323 (Div. 2) C.GCD Table

    C. GCD Table The GCD table G of size n × n for an array of positive integers a of length n is define ...

  10. Hawk: 无编程抓取淘女郎的所有高清照片

    1.这是什么鬼? 哦?美女? 最近看了这一篇文章:http://cuiqingcai.com/1001.html 大概说的是用Python和Pyspider(这货好像是我的一位师兄写的,吓尿),抓取淘 ...