原文连接:https://www.entityframeworktutorial.net/entityframework6/custom-conventions-codefirst.aspxhtml
EF 6 Code-First系列文章目录:数据库
在前面的章节中,你以及学习了Code-First默认的约定。EF 6一样也让你本身定义自定义的约定,而后你的实体就会遵循这个自定义的约定的行为。app
这里有两种类型的约定:配置约定(Configuration Conventions)和模型约定(Model Conventions).ide
配置约定学习
配置约定就是不重写Fluent API提供实体的默认的行为,给实体进行配置。你能够在OnModelCreating方法中定义配置约定,还能够像Fluent API配置普通的实体映射那样,在自定义的类中配置约定。测试
例如,若是你想要给属性名称为{实体名称}_ID的属性,配置主键,能够像下面这样:ui
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】spa
下面的代码,为string类型的属性定义了一个约定。它将会建立nvarchar类型的列,大小是50。.net
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<PKConvention>(); }
模型约定
模型约定是基于模型元数据的。这里有关于CSDL和SSDL的约定,建立一个类,实现CSDL约定中的IConceptualModelConvention 接口,或者实现SSDL约定中的IStoreModelConvention
接口。
想要了解更多EF 6 自定义约定相关的,能够看看这篇文章: Custom Convention in EF 6 。