礼仪之邦官网,黄柳武,沈阳兼职女qq
我们已经知道了在onmodelcreating()方法中可以通过fluentapi对所有的实体类进行配置,然而当实体类很多时,我们把所有的配置都放在onmodelcreating()方法中很难维护。ef6允许我们给每一个实体添加一个单独的配置类,通过这个配置类来对相应的实体进行配置。
以配置student实体类为例,我们在onmodelcreating()方法中配置student实体,代码如下:
public class schooldbcontext: dbcontext { public schooldbcontext(): base() { } public dbset<student> students { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<student>().totable("studentinfo"); modelbuilder.entity<student>().haskey<int>(s => s.studentkey); modelbuilder.entity<student>() .property(p => p.dateofbirth) .hascolumnname("birthday") .hascolumnorder(3) .hascolumntype("datetime2"); modelbuilder.entity<student>() .property(p => p.studentname) .hasmaxlength(50); modelbuilder.entity<student>() .property(p => p.studentname) .isconcurrencytoken(); modelbuilder.entity<student>() .hasmany<course>(s => s.courses) .withmany(c => c.students) .map(cs => { cs.mapleftkey("studentid"); cs.maprightkey("courseid"); cs.totable("studentcourse"); }); } }
我们可以将每个实体类的配置放在一个对应的的配置类,(如studnet的实体配置在studententityconfiguratinos配置类中),如果程序中有很多实体类,采用单独配置的方式可以很好的提高配置的可维护性和可读性。
步骤如下:
步骤①:创建一个studententityconfiguratinos类,这个类继承 entitytypeconfiguration<tentity> ,代码如下:
public class studententityconfiguration: entitytypeconfiguration<student> { public studententityconfiguration() { this.totable("studentinfo"); this.haskey<int>(s => s.studentkey); this.property(p => p.dateofbirth) .hascolumnname("dob") .hascolumnorder(3) .hascolumntype("datetime2"); this.property(p => p.studentname) .hasmaxlength(50); this.property(p => p.studentname) .isconcurrencytoken(); this.hasmany<course>(s => s.courses) .withmany(c => c.students) .map(cs => { cs.mapleftkey("studentid"); cs.maprightkey("courseid"); cs.totable("studentcourse"); }); } }
步骤②: 在onmodelcreating()方法中使用上边的配置类:
public class schooldbcontext: dbcontext { public schooldbcontext(): base() { } public dbset<student> students { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { // 添加student实体的配置 modelbuilder.configurations.add(new studententityconfiguration()); } }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论