一、新建一個解決方案,包含兩個項目: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)); } } DataModelContext
五、在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();//可以分次提交,也可以最後一次性提交給數據庫 } } DataModelInitializer
六、編輯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> app.config
七、編輯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(); } Main()
八、一切准備就緒,按F5,歡快的跑起來吧!
如果程序運行不起來,請先檢查app.config文件中ConnectionString的設置是否正確(例如MySQL服務器地址、端口),再檢查MySQL服務是否已開啟。
九、最後我們來查看一下自動生成的數據表結構及初始化時填充的數據
源代碼已經托管到OSChina:http://git.oschina.net/xant77/EF6CodeFirstSimpleDemo