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

本文共 1296 字,大约阅读时间需要 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);}

同样你可以定义数据类型的大小的约定。下面的代码,为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/

你可能感兴趣的文章
PYTHON--欧拉习题二
查看>>
python--高级应用总结
查看>>
python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
查看>>
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>
Python写表情包搜索工具(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Python-【1】配置
查看>>
Python-从子文件夹执行绝对导入
查看>>