博客
关于我
19.翻译系列:EF 6中定义自定义的约定【EF 6 Code-First约定】
阅读量:416 次
发布时间:2019-03-06

本文共 1464 字,大约阅读时间需要 4 分钟。

原文链接:

 

EF 6 Code-First系列文章目录:

 

  • )
  • )
  • )
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        
  •        

 

在前面的章节中,你以及学习了Code-First默认的约定。EF 6同样也让你自己定义自定义的约定,然后你的实体就会遵循这个自定义的约定的行为。

这里有两种类型的约定:配置约定(Configuration Conventions)和模型约定(Model Conventions).

 

配置约定

 

配置约定就是不重写Fluent API提供实体的默认的行为,给实体进行配置。你可以在OnModelCreating方法中定义配置约定,还可以像Fluent API配置普通的实体映射那样,在自定义的类中配置约定。

例如,如果你想要给属性名称为{实体名称}_ID的属性,配置主键,可以像下面这样:

protected override void OnModelCreating(DbModelBuilder modelBuilder){    modelBuilder        .Properties()        .Where(p => p.Name == p.DeclaringType.Name + "_ID")        .Configure(p => p.IsKey());    base.OnModelCreating(modelBuilder);}

同样你可以定义数据类型的大小的约定【data type of size】

下面的代码,为string类型的属性定义了一个约定。它将会创建nvarchar类型的列,大小是50。

protected override void OnModelCreating(DbModelBuilder modelBuilder){        modelBuilder            .Properties()            .Where(p => p.PropertyType.Name == "String")            .Configure(p => p.HasMaxLength(50));    base.OnModelCreating(modelBuilder);}

当然,你可以在单独的类中,定义这些约定,这个自定义的类需要继承自Convention类,例如:

public class PKConvention : Convention{    public PKConvention()    {        .Properties()        .Where(p => p.Name == p.DeclaringType.Name + "_ID")        .Configure(p => p.IsKey());    }}

添加完自定义的类,然后在OnModelCreating方法中这样用:

protected override void OnModelCreating(DbModelBuilder modelBuilder){    modelBuilder.Conventions.Add
();}

 

模型约定

 

模型约定是基于模型元数据的。这里有关于CSDL和SSDL的约定,创建一个类,实现CSDL约定中的IConceptualModelConvention 接口,或者实现SSDL约定中的IStoreModelConvention 接口。

想要了解更多EF 6 自定义约定相关的,可以看看这篇文章:  。

 

转载地址:http://uvxkz.baihongyu.com/

你可能感兴趣的文章
ng6.1 新特性:滚回到之前的位置
查看>>
nghttp3使用指南
查看>>
【Flink】Flink 2023 Flink 自动化运维的大规模落地实践
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(一)—— 组件介绍
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx 301跳转
查看>>
nginx 403 forbidden
查看>>
nginx connect 模块安装以及配置
查看>>