应用场景

场景一:EF Code First默认使用类名作为表名,如果我们需要给表名加个前缀,例如将类名Category映射到表Shop_Category、将Product映射到Shop_Product,在EF 6之前,只能一个一个地使用Data Annotation( [Table("Shop_Category")] )或者Fluent API( ToTable("Shop_Category") )一个一个地指定表名。在实体类数量比较多的情况下,工作量就比较大了。

场景二:EF Code First默认将String类型的属性映射为nvarchar(max),但是你可能想要将它映射为nvarchar(255),那么也可以全局性地自定义,而不需要在所有String类型的属性上面使用[MaxLength(255)]进行配置。

当然使用场景不只这两个,如改写主外键的映射规则等等。简而言之,Custom Code First Conventions使你能够改写Entity Framework模型与数据库之间默认的映射规则。

自定义Code First约定的方式

Code First的默认映射规则可以通过三种方式进行自定义,分别是:Lightweight Conventions(轻量级约定)、Configuration Conventions(配置型约定)、Model-based Conventions(基于模型的配置)。实现上的复杂度由Lightweight Conventions开始依次递增,当然,实现的自由度也依次增大。

 1 public class ProductContext : DbContext
2 {
3 static ProductContext()
4 {
5 Database.SetInitializer(
6 new DropCreateDatabaseIfModelChanges<ProductContext>());
7 }
8
9 public DbSet<Product> Products { get; set; }
10 }
11
12 public class Product
13 {
14 public int ProductId { get; set; }
15 public string Name { get; set; }
16 public string? Description {get; set;}
17 }

在这个模型中,默认情况下,EF会生成以下的数据表结构:

表名:Product
字段名称 类型 是否可空
ProductId int 主键
Name nvarchar(max)
Description nvarchar(max)

我们以添加表前缀为例,来说明自定义Code First约定的前两种方式。

Lightweight Conventions

重写ProductContext的OnModelCreating(DbModelBuilder modelBuilder)方法:

1 public class ProductContext : DbContext
2 {
3 protected override void OnModelCreating(DbModelBuilder modelBuilder)
4 {
5 modelBuilder.Types().Configure(entity => entity.ToTable("Shop_" + entity.ClrType.Name));
6 }
7 }

Lightweight Conventions是最简单的实现方式,大部分的全局配置需求都能够以这种方式来实现。

Configuration Conventions

实现IConfigurationConvention<Type, EntityTypeConfiguration>接口,然后重写ProductContext的OnModelCreating(DbModelBuilder modelBuilder)方法。

 1 public class DefaultTableConvention
2 : IConfigurationConvention<Type, EntityTypeConfiguration>
3 {
4 public void Apply(
5 Type type,
6 Func<EntityTypeConfiguration> configuration)
7 {
8 TableAttribute[] tableAttributes = (TableAttribute[])type.GetCustomAttributes(typeof(TableAttribute), false);
9
10 if (tableAttributes.Length == 0)
11 {
12 configuration().ToTable("Shop_" + type.Name);
13 }
14 }
15 }
16
17 public class ProductContext : DbContext
18 {
19 protected override void OnModelCreating(DbModelBuilder modelBuilder)
20 {
21 modelBuilder.Conventions.Add<DefaultTableConvention>();
22 }
23 }

从上面的代码可以看到,Configuration Conventions的方式需要自行判断实体是否使用TableAttribute指定了表名,如果是,则不使用全局的配置。而Lightweight Conventions则默认优先使用TableAttribute指定的表名。可以看出,Configuration Conventions实现起来相对繁琐了一点,但是自由度也更高。

IConfigurationConvention接口有两个类型参数:TMemberInfo和TConfiguration。它们用来过滤你想自定义约定的模型元素。

第一个类型参数,TMemberInfo,可以是一下两个值:

  • Type(System)

  • PropertyInfo(System.Reflection)

第二个类型参数,TConfiguration,可以是一下任意一种。

  • ModelConfiguration (System.Data.Entity.ModelConfiguration.Configuration)

  • EntityTypeConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Types)

  • PropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties)

  • NavigationPropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation)

  • PrimitivePropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

    • DateTimePropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

    • DecimalPropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

    • LengthPropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

      • BinaryPropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

      • StringPropertyConfiguration (System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive)

注意,Type和PropertyConfiguration(以及它的子类)不能混用,否则Configuration Conventions将不会生效。

增加自定义的Data Annotation

利用Custom Code First Conventions,我们还可以扩展自己的Data Annotation。例如,增加一个EmailAttribute特性,然后在Lightweight Conventions或者Configuration Conventions中,判断属性是否应用了EmailAttribute特性;如果是,则将列名映射为“Email”,列类型映射为“nvarchar(255)”, 达到了[Column("Email")]和[MaxLength(255)]共同作用的效果。

【EF】Entity Framework 6新特性:全局性地自定义Code First约定的更多相关文章

  1. Entity Framework 6新特性:全局性地自定义Code First约定

    2012年12月11日,Entity Framework已经发布了Entity Framework 6 Alpha2,因项目需要,目前已使用了其中的两个特性,今天就来介绍一下第一个特性:全局性地自定义 ...

  2. [转]Entity Framework走马观花之把握全局

    本文转自:http://blog.csdn.net/bitfan/article/details/12887007 Entity Framework走马观花 之 把握全局 ============== ...

  3. EF(Entity Framework)多对多关系下用LINQ实现"NOT IN"查询

    这是今天在实际开发中遇到的一个问题,需求是查询未分类的博文列表(未加入任何分类的博文),之前是通过存储过程实现的,今天用EF实现了,在这篇博文中记录一下. 博文的实体类BlogPost是这样定义的: ...

  4. [转载]灵动思绪EF(Entity FrameWork)

    很久之前就想写这篇文章了,但是由于种种原因,没有将自己学习的EF知识整理成一片文章.今天我就用CodeFirst和ModelFirst两种方式的简单案例将自己学习的EF知识做个总结. 在讲解EF之前, ...

  5. EF(Entity Framework)通用DBHelper通用类,增删改查以及列表

    其中 通用类名:DBhelper 实体类:UserInfo 1 //新增 2 DBHelper<UserInfo> dbhelper = new DBHelper<UserInfo& ...

  6. Entity Framework 实体框架的形成之旅--Code First模式中使用 Fluent API 配置(6)

    在前面的随笔<Entity Framework 实体框架的形成之旅--Code First的框架设计(5)>里介绍了基于Code First模式的实体框架的经验,这种方式自动处理出来的模式 ...

  7. Entity Framework 实体框架的形成之旅--Code First的框架设计(5)

    在前面几篇介绍了Entity Framework 实体框架的形成过程,整体框架主要是基于Database First的方式构建,也就是利用EDMX文件的映射关系,构建表与表之间的关系,这种模式弹性好, ...

  8. 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片

    [源码下载] 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片 作者:webabcd 介绍重新想象 Win ...

  9. Entity Framework走马观花之把握全局 (转)

    上一篇<Entity Framework技术导游系列开篇与热身 > ========================================= 在深入学习某项技术之前,应该努力形成 ...

随机推荐

  1. 牛客小白赛4J——强迫症

    链接:https://www.nowcoder.com/acm/contest/134/J 来源:牛客网 思路:把数列排序,把每一个重复的元素和最后一个数想加得到新数,在删掉这一元素即为去重的最少步骤 ...

  2. 【转】odoo 10的企业微信发送程序介绍

    本文介绍的微信发送程序不是独立的模块,是某企业应用的一部分, 源码可在京津冀odoo技术交流群的群共享中下载.   [1]基本配置 在work.weixin.qq.com上注册一个企业后,会得到企业的 ...

  3. Android Parcelable 源码解析

    大家都知道,要想在Intent里面传递一些非基本类型的数据,有两种方式,一种实现Parcelable,另一种是实现Serializable接口. 今天先不说Serializable 接口,只说Parc ...

  4. 解决replace格式替换后光标定位问题

    场景:格式化银行卡444格式 手机号344格式 身份证号684格式 校验数据格式,replace后光标定位错乱 或光标一直定位在最后 解决,只针对input,代码用的vue: 获取光标位置: getC ...

  5. 安装MySQLdb模块遭遇"fatal error: my_config.h: No such file or directory"的处理

    Issue       I encountered an error when I run the python script which need to import the module of & ...

  6. 自己来编写一份 Python 脚本 第一版

    解决问题 我们已经探索了 Python 语言中的许多部分,现在我们将通过设计并编写一款程序来了解如何把这些部分组合到一起.这些程序一定是能做到一些有用的事情.这节的Python教程就是教大家方法去学习 ...

  7. Python全栈 Web(边框、盒模型、背景)

    原文地址 https://yq.aliyun.com/articles/634926 ......................................................... ...

  8. [Clr via C#读书笔记]Cp19可空值类型

    Cp19可空值类型 主要解决的是和数据库中null对应的问题: System.Nullable结构:值类型: int?语法: 可空实例能够使用操作符: C#空合并操作符??; 即可用于引用类型,也可以 ...

  9. Python中函数的参数-arguments

    归纳起来,Python中函数的定义形式和调用形式主要有如下几种形式: # 函数的定义形式 def func(name) # 匹配positional参数或者keyword参数 def func(nam ...

  10. Python字符串格式化表达式和格式化方法

    Python格式化字符串由两种方式可以选择:一种是格式化表达式(Formatting Expression),一种是格式化方法(Formatting Method).其中格式化表达式在全Python版 ...