机动车驾驶员科目一,尸头,高考阳光信息平台
原文链接:
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<pkconvention>(); }
模型约定
模型约定是基于模型元数据的。这里有关于csdl和ssdl的约定,创建一个类,实现csdl约定中的iconceptualmodelconvention 接口,或者实现ssdl约定中的istoremodelconvention
接口。
想要了解更多ef 6 自定义约定相关的,可以看看这篇文章: custom convention in ef 6 。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论