EF6配合MySQL或MSSQL(CodeFirst模式)配置指引
时间:2015-02-10 13:04:52
收藏:0
阅读:11872
一、新建一个解决方案,包含两个项目:EF6CodeFirstMySQL.Model(动态库项目),EF6CodeFirstMySQL.Tests(控制台应用)
二、通过NuGet将EntityFramework6及MySql.Data.Entity包引入解决方案(两个项目都要引入)
三、在Model项目中添加三个类,BaseBill,Contract,DeliveryNote,后面两个类从BaseBill类继承。(代码参见附件)
四、在Model项目中添加DataModelContext类,继承自DbContext
public class DataModelContext : DbContext { public DataModelContext() : base("DataModelContext")//web.config中connectionstring的名字 { } public DbSet<Contract> Contracts { get; set; } public DbSet<DeliveryNote> DeliveryNotes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //指定单数形式的表名 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //物理表名添加xx前綴 modelBuilder.Types().Configure(f => f.ToTable("xx" + f.ClrType.Name)); } }
五、在Model项目中添加DataModelInitializer类,用于初始化数据库中的数据
public class DataModelInitializer : DropCreateDatabaseIfModelChanges<DataModelContext> // CreateDatabaseIfNotExists<DataModelContext> { protected override void Seed(DataModelContext context) { var contracts = new List<Contract> { new Contract{ BillNo = "PO20150201-001", BillDate=new DateTime(2015, 2, 1), TotalPrice=9876543.21M, Supplier = "Microsoft"}, new Contract{ BillNo = "PO20141230-088", BillDate=new DateTime(2014, 12, 30), TotalPrice=1234567.89M, Supplier = "Oracle"}, }; context.Contracts.AddRange(contracts); context.SaveChanges();//可以分次提交,也可以最后一次性提交给数据库 var deliveries = new List<DeliveryNote> { new DeliveryNote{ BillNo = string.Format("DN{0:yyyyMMdd}-006", DateTime.Today), TotalPrice=445566M, Contract=contracts.First(), Checker="张三"}, }; context.DeliveryNotes.AddRange(deliveries); context.SaveChanges();//可以分次提交,也可以最后一次性提交给数据库 } }
六、编辑app.config配置文件(注意:实际使用的配置文件为应用程序项目中的app.config或web.config,动态库项目中的app.config在运行时不起作用)
<?xml version="1.0" encoding="utf-8"?> <!--注意:此项目为动态库,所以此配置文件内容仅供作为范本使用,实际的WPF或ASP.NET项目可从此文件复制配置内容进行修改--> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <!--MySQL启用下面一行--> <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6"> <!--SQL SERVER 启用下面一行--> <!--entityFramework--> <contexts> <!--通过设置disableDatabaseInitialization="true",可以禁止数据库初始化操作--> <context type="EF6CodeFirstMySQL.Model.DataModelContext,EF6CodeFirstMySQL.Model" disableDatabaseInitialization="false"> <databaseInitializer type="EF6CodeFirstMySQL.Model.DataModelInitializer,EF6CodeFirstMySQL.Model"></databaseInitializer> </context> </contexts> <!--MySQL启用下面一段配置项--> <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> <!--SQL SERVER 启用下面一行--> <!--defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /--> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider> </providers> </entityFramework> <connectionStrings> <!--MySQL启用下面一行--> <add name="DataModelContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=EF6CodeFirstDemo;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" /> <!--SQL SERVER 启用下面一行,注意数据库文件路径中使用了|DataDirectory|宏变量,该变量只在ASP.NET项目中有效--> <!--add name="DataModelContext" connectionString="Data Source=.;database=EF6CodeFirstDemo;uid=sa;pwd=123456;AttachDBFilename=|DataDirectory|\XantFlowDB.mdf;" providerName="System.Data.SqlClient"/--> </connectionStrings> <system.data> <DbProviderFactories> <remove invariant="MySql.Data.MySqlClient" /> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data> </configuration>
七、编辑Tests项目中的Program.Main()方法,从数据库中读取数据并在控制台显示
static void Main(string[] args) { using(var ctx = new DataModelContext()) { foreach (DeliveryNote dn in ctx.DeliveryNotes.Include("Contract")) { Console.WriteLine(string.Format("送货单号:{0},送货日期:{1:yyyy-MM-dd},到货金额:{2:#0,000.00},合同编号:{3},供应商:{4},合同总金额:{5},合同总金额(直接属性):{6}", dn.BillNo, dn.BillDate, dn.TotalPrice, dn.Contract.BillNo, dn.Contract.Supplier, dn.Contract.TotalPrice, dn.ContractTotalPrice)); } } Console.WriteLine("\n\n按[回车]键退出..."); Console.ReadLine(); }
八、一切准备就绪,按F5,欢快的跑起来吧!
如果程序运行不起来,请先检查app.config文件中ConnectionString的设置是否正确(例如MySQL服务器地址、端口),再检查MySQL服务是否已开启。
九、最后我们来查看一下自动生成的数据表结构及初始化时填充的数据
源代码已经托管到OSChina:http://git.oschina.net/xant77/EF6CodeFirstSimpleDemo
评论(0)