初次使用Entity Framework(以下简称EF),为了避免很快忘记,决定开日志记录学习过程和遇到的问题。
因为项目比较小,只会用到EF的一些基本功能,因此先在此处制定一个学习目标:
1. 配置EF(指定EF用哪个数据库,相信在大部分开发过程中都不会使用官方Demo中的LocalDb)
2. 根据代码生成表(主要是一些特殊情况,比如希望自己设置string类型属性的长度,不想统一都是nvarchar(max))
3. 生成视图(部分类其实希望生成成为视图,这样可以让数据库表设计更加符合范式,同时简化查询,不知道能不能实现)
4. 生成数据库脚本和变更脚本(对于Code First的方式来说,这一步也是相当重要的,否则就没有Code First的意义了)
怎样获取EF,怎样添加EF到项目里去这里就不说了,使用NuGet是一个相对简单的方式,不清楚可以看官方的说明。添加完EF之后就需要对EF进行配置了,通常这时候配置文件里已经自动添加上默认的EF配置节点了,如果新建的是命令行程序,那配置文件应该就是这样:
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 5 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 6 </configSections> 7 <entityFramework> 8 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 9 <parameters> 10 <parameter value="v11.0" /> 11 </parameters> 12 </defaultConnectionFactory> 13 <providers> 14 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 15 </providers> 16 </entityFramework> 17 </configuration>