EF6 with MySQL or MSSQL (Codefirst mode) configuration guidelines

Source: Internet
Author: User
Tags file copy mssql connectionstrings

First, a new solution, including two projects: Ef6codefirstmysql.model (Dynamic Library project), Ef6codefirstmysql.tests (console application)

Ii. introducing EntityFramework6 and MySql.Data.Entity packages to the solution through NuGet (two projects to be introduced)

Third, add three classes to the model project, Basebill,contract,deliverynote, and the following two classes inherit from the Basebill class. (see attachment for code)

Iv. adding the Datamodelcontext class to the model project, inheriting from DbContext

     Public classDatamodelcontext:dbcontext { PublicDatamodelcontext ():Base("Datamodelcontext")//connectionstring name in Web. config        {        }         PublicDbset<contract> Contracts {Get;Set; }  PublicDbset<deliverynote> DeliveryNotes {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {//Specify a table name in the singular formModelbuilder.conventions.remove<pluralizingtablenameconvention>(); //Physical table name add xx before ableModelbuilder.types (). Configure (f = f.totable ("xx"+f.clrtype.name)); }    }
Datamodelcontext

V. Add the Datamodelinitializer class to the model project to initialize the data in the database

     Public classDatamodelinitializer:dropcreatedatabaseifmodelchanges<datamodelcontext>//createdatabaseifnotexists<datamodelcontext>    {        protected Override voidSeed (Datamodelcontext context) {varContracts =NewList<contract>            {                Newcontract{Billno ="po20150201-001", billdate=NewDateTime ( -,2,1), totalprice=9876543.21M, Supplier ="Microsoft"},                Newcontract{Billno ="po20141230-088", billdate=NewDateTime ( the, A, -), totalprice=1234567.89M, Supplier ="Oracle"},            }; Context.            Contracts.addrange (contracts); Context. SaveChanges ();//can be submitted in a single submission, or it can be submitted to the database at once            varDeliveries =NewList<deliverynote>            {                Newdeliverynote{Billno =string. Format ("dn{0:yyyymmdd}-006", Datetime.today), totalprice=445566m, contract=contracts. First (), checker="Zhang San"},            }; Context.            Deliverynotes.addrange (deliveries); Context. SaveChanges ();//can be submitted in a single submission, or it can be submitted to the database at once        }    }
Datamodelinitializer

Vi. Edit the App. Config profile (Note: The actual configuration file used is app. config or Web. config in the application project, and app. config in the Dynamic Library project does not work at run time)

<?XML version= "1.0" encoding= "Utf-8"?><!--Note: This project is a dynamic library, so this profile content is intended for use as a template, and the actual WPF or ASP. NET project can be modified from this file copy configuration -<Configuration>  <configsections>    <!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -    < Sectionname= "EntityFramework"type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, culture= Neutral, publickeytoken=b77a5c561934e089 "requirepermission= "false" />  </configsections>  <!--MySQL enables the following line -  <EntityFrameworkCodeconfigurationtype= "MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">  <!--SQL SERVER enables the following line -  <!--EntityFramework -    <Contexts>      <!--You can disable the initialization of a database by setting disabledatabaseinitialization= "true" -      <Contexttype= "Ef6codefirstmysql.model.datamodelcontext,ef6codefirstmysql.model"disabledatabaseinitialization= "false">        <Databaseinitializertype= "Ef6codefirstmysql.model.datamodelinitializer,ef6codefirstmysql.model"></Databaseinitializer>      </Context>    </Contexts>    <!--MySQL enables the following section of configuration items -    <defaultconnectionfactorytype= "MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6">      <Parameters>        <parametervalue= "v11.0" />      </Parameters>    </defaultconnectionfactory>    <!--SQL SERVER enables the following line -    <!--defaultconnectionfactory type= "System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/  -    <providers>      <providerInvariantName= "System.Data.SqlClient"type= "System.Data.Entity.SqlServer.SqlProviderServices, entityframework.sqlserver" />      <providerInvariantName= "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 enables the following line -    <Addname= "Datamodelcontext"connectionString= "Data source=localhost;port=3306;initial catalog=ef6codefirstdemo;user id=root;password=123456;"ProviderName= "MySql.Data.MySqlClient" />    <!--SQL SERVER enables the following line, noting that the database file path is used in the | datadirectory| macro variable, which is valid only in ASP. -    <!--add Name= "Datamodelcontext" connectionstring= "Data source=.; database=ef6codefirstdemo;uid=sa;pwd=123456; attachdbfilename=| Datadirectory|\xantflowdb.mdf, "providername=" System.Data.SqlClient "/ -  </connectionStrings>  <System.Data>    <dbproviderfactories>      <Removeinvariant= "MySql.Data.MySqlClient" />      <Addname= "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.

Edit the Program.main () method in the tests project to read the data from the database and display it in the console

        Static voidMain (string[] args) {            using(varCTX =NewDatamodelcontext ()) {                foreach(Deliverynote DNinchCTx. Deliverynotes.include ("Contract") {Console.WriteLine (string. Format ("Delivery ticket: {0}, delivery date: {1:YYYY-MM-DD}, Arrival amount: {2: #0, 000.00}, contract number: {3}, Vendor: {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 ("\ nyou Press [Enter] key to exit ...");        Console.ReadLine (); }
Main ()

Eight, all ready, press F5, Merry run up!

If the program does not work, check that the ConnectionString settings in the App. Config file are correct (for example, MySQL server address, port), and then check that the MySQL service is turned on.

Ix. Finally, let's look at the structure of the automatically generated data table and the data that is populated when initialized

The source code is already hosted on the Oschina:http://git.oschina.net/xant77/ef6codefirstsimpledemo

EF6 with MySQL or MSSQL (Codefirst mode) configuration guidelines

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.