EF6 works with MySQL or MSSQL (CodeFirst mode) Configuration Guide, ef6codefirst

Source: Internet
Author: User

EF6 works with MySQL or MSSQL (CodeFirst mode) Configuration Guide, ef6codefirst

1. Create a solution that includes two projects: EF6CodeFirstMySQL. Model (dynamic library project) and EF6CodeFirstMySQL. Tests (console application)

 

2. Introduce EntityFramework6 and MySql. Data. Entity packages into the solution through NuGet (both projects must be introduced)

 

3. Add three classes in the Model Project: BaseBill, Contract, and DeliveryNote. The latter two classes are inherited from the BaseBill class. (See attachment for code)

 

4. Add the DataModelContext class to the Model project and inherit from DbContext.

Public class DataModelContext: DbContext {public DataModelContext (): base ("DataModelContext") // web. the connectionstring name in config {} public DbSet <Contract> Contracts {get; set;} public DbSet <DeliveryNote> DeliveryNotes {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {// specify the table name modelBuilder in the singular form. conventions. remove <PluralizingTableNameConvention> (); // The Name Of The physical table before xx is added. types (). configure (f => f. toTable ("xx" + f. clrType. name ));}}DataModelContext

 

5. Add the DataModelInitializer class to the Model project to initialize data in the database.

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.21 M, supplier = "Microsoft"}, new Contract {BillNo = "PO20141230-088", BillDate = new DateTime (2014, 12, 30), TotalPrice = 1234567.89 M, supplier = "Oracle" },}; context. contracts. addRange (contracts); context. saveChanges (); // The SaveChanges can be submitted in multiple stages or to the database var deliveries = new List <DeliveryNote> {new DeliveryNote {BillNo = string. format ("DN {0: yyyyMMdd}-006", DateTime. today), TotalPrice = 445566 M, Contract = contracts. first (), Checker = "Michael"},}; context. deliveryNotes. addRange (deliveries); context. saveChanges (); // The SaveChanges can be submitted in multiple stages, or submitted to the database at one time }}DataModelInitializer

 

6. Edit the app. config configuration file (note: the configuration file used is the app in the application project. config or web. config, the app in the dynamic library project. config does not work at runtime)

<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Note: This project is a dynamic library, so the configuration file content is only used as a template, the actual WPF or ASP.. NET project can be modified by copying configuration content from this file --> <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> <! -- Enable the following MySQL line --> <entityFramework codeConfigurationType = "MySql. Data. Entity. MySqlEFConfiguration, MySql. Data. Entity. EF6"> <! -- Enable the following line on SQL SERVER --> <! -- EntityFramework --> <contexts> <! -- Disable database initialization by setting disableDatabaseInitialization = "true" --> <context type = "EF6CodeFirstMySQL. model. dataModelContext, EF6CodeFirstMySQL. model "disableDatabaseInitialization =" false "> <databaseInitializer type =" EF6CodeFirstMySQL. model. dataModelInitializer, EF6CodeFirstMySQL. model "> </databaseInitializer> </context> </contexts> <! -- MySQL enables the following configuration item --> <defaconnecticonnectionfactory type = "MySql. data. entity. mySqlConnectionFactory, MySql. data. entity. EF6 "> <parameters> <parameter value =" v11.0 "/> </parameters> </defaconnecticonnectionfactory> <! -- Enable the following line on 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, Cul Ture = neutral, PublicKeyToken = c5687fc88969c44d "> </provider> </providers> </entityFramework> <connectionStrings> <! -- MySQL enables the following line --> <add name = "DataModelContext" connectionString = "Data Source = localhost; port = 3306; Initial Catalog = EF6CodeFirstDemo; user id = root; password = 123456; "providerName =" MySql. data. mySqlClient "/> <! -- SQL SERVER enables the following row. Note that | DataDirectory | macro variable is used in the database file path. This variable is only valid in ASP. NET projects. --> <! -- 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

 

7. Edit the Program. Main () method in the Tests project, read data from the database, and display it on the console.

Static void Main (string [] args) {using (var ctx = new DataModelContext () {foreach (DeliveryNote dn in ctx. deliveryNotes. include ("Contract") {Console. writeLine (string. format ("Delivery Order No.: {0}, delivery date: {1: yyyy-MM-dd}, delivery amount: {2: #0,000.00}, Contract No.: {3 }, supplier: {4}, total contract amount: {5}, total contract amount (direct attribute): {6} ", dn. billNo, dn. billDate, dn. totalPrice, dn. contract. billNo, dn. contract. supplier, dn. contract. totalPrice, dn. contractTotalPrice);} Console. writeLine ("\ n press [Press enter] to exit... "); Console. readLine ();}Main ()

 

8. Everything is ready. Press F5 and start happily!

If the program cannot run, first check whether the ConnectionString settings in the app. config file are correct (for example, the MySQL server address and port), and then check whether the MySQL service is enabled.

 

9. Finally, let's take a look at the automatically generated data table structure and the data filled during initialization.

 

Source code has been hosted on OSChina: http://git.oschina.net/xant77/EF6CodeFirstSimpleDemo

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.