原文链接:https://www.entityframeworktutorial.net/entityframework6/custom-conventions-codefirst.aspx
在前面的章节中,你以及学习了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<PKConvention>();
}
模型约定
模型约定是基于模型元数据的。这里有关于CSDL和SSDL的约定,创建一个类,实现CSDL约定中的IConceptualModelConvention 接口,或者实现SSDL约定中的IStoreModelConvention
接口。
想要了解更多EF 6 自定义约定相关的,可以看看这篇文章: Custom Convention in EF 6 。
19.翻译系列:EF 6中定义自定义的约定【EF 6 Code-First约定】
原文:https://www.cnblogs.com/caofangsheng/p/10705099.html