ASP.NET MVC 4 EF5 with MySQL

前端 未结 3 845
半阙折子戏
半阙折子戏 2020-12-07 16:52

So I\'ve just picked up VS2012 and I want to start an ASP.NET MVC 4 app with EF5.

My host does not have MSSQL so I have to use MySQL.

How do I tell my app th

相关标签:
3条回答
  • 2020-12-07 17:31

    You need to setup your config with a connection string, DbProviderFactory and a custom DatabaseInitializer for MySql Connector 6.5.4. I have detailed the full step for getting EF5 and MySql to play, including code for the initializers on my blog. If you require ASP.Net membership provider solution it been asked before: ASP.NET Membership/Role providers for MySQL? I will post the solution here also for a complete EF5 MySql solution.

    The MySql connector does not currently support EF 5 migration and ASP.NET only supports SimpleMembership (MVC4 default) on MS SQL not MySql. The solution below is for Code First.

    The steps are:

    1. Grab EF 5 from NuGet
    2. Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4)
    3. Configure a MySql Data Provider
    4. Configure a MySql Connection String
    5. Create a Custom MySql Database Initializer
    6. Configure the Custom MySql Database Initializer
    7. Configure ASP.NET membership if you require it

    DbProvider

    <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" />
     </DbProviderFactories>
    </system.data>
    

    Connection String

    <connectionStrings>
      <add name="ConnectionStringName" 
        connectionString="Datasource=hostname;Database=schema_name;uid=username;pwd=Pa$$w0rd;" 
        providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    

    Database Initializer

    If you are using MySql connector from NuGet (6.5.4) then a custom initializer is required. Code available at http://brice-lambson.blogspot.se/2012/05/using-entity-framework-code-first-with.html or at http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/

    Then add this to configuration

    <configSections>
      <section name="entityFramework" 
        type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, 
        EntityFramework, Version=5.0.0.0, Culture=neutral, 
        PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <entityFramework>
      <contexts>
          <context type="Namespace.YourContextName, AssemblyName">
             <databaseInitializer 
               type="Namespace.YourChosenInitializer, AssemblyName">
             </databaseInitializer>
          </context>
        </contexts>
        <defaultConnectionFactory 
          type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data" />
    </entityFramework>
    

    ASP.NET Membership

    <membership defaultProvider="MySqlMembershipProvider">
      <providers>
        <clear />
        <add name="MySqlMembershipProvider"
             type="MySql.Web.Security.MySQLMembershipProvider,
             MySql.Web, Version=6.5.4.0, PublicKeyToken=c5687fc88969c44d"
         autogenerateschema="true"
         connectionStringName="*NAME_OF_YOUR_CONN_STRING*"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         requiresUniqueEmail="false"
         passwordFormat="Hashed"
         maxInvalidPasswordAttempts="5"
         minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10"
         passwordStrengthRegularExpression=""
         applicationName="/" />
      </providers>
    </membership>
    

    Get the AccountController and Views working:

    1. Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view
    2. Create a new MVC 3 web application
    3. Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application
    4. Replace @Html.Partial(“_LoginPartial”) in the shared _Layout view with @Html.Partial(“_LogOnPartial”)
    0 讨论(0)
  • 2020-12-07 17:34

    Install Package:

    PM> Install-Package EntityFramework
    PM> Update-Package EntityFramework
    PM> Install-Package MySql.Data.Entity
    

    Web.config

    <connectionStrings>
     <add name="DefaultConnection"
       providerName="MySql.Data.MySqlClient"
       connectionString="Data Source=localhost;port=3306;Initial Catalog=api_db;User Id=root;password=''"/>
    </connectionStrings>
    

    Create Model Class

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace LiteRemit.Models
    {
        [Table("customers")]
        public class CustomerModel
        {
            [Key]
            public int CustomerId { get; set; }
            public string Name { get; set; }
            public string Country { get; set; }
        }
    }
    

    Create Model Context:

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    
    namespace LiteRemit.Models
    {
        public class MySqlCon : DbContext
        {
            //MySql Database connection String
            public MySqlCon() : base(nameOrConnectionString: "DefaultConnection") { }
            public virtual DbSet<CustomerModel> Customers { get; set; }
        }
    }
    

    Create Controller Class

    using LiteRemit.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace LiteRemit.Controllers
    {
        public class HomeController : Controller
        {
            MySqlCon _con;
            public HomeController()
            {
                _con = new MySqlCon();
            }
    
            public ActionResult Index()
            {
                return View(_con.Customers.ToList());
            }
     }
    }
    

    Code add view page:

    @using LiteRemit.Models
    @model IEnumerable<CustomerModel>
    
    <table border="1">
     @foreach (var item in Model)
     {
      <tr>
       <td>@Html.DisplayFor(modelItem => item.CustomerId)</td>
       <td>
        @Html.DisplayFor(modelItem => item.Name)
       </td>
       <td>@Html.DisplayFor(modelItem => item.Country)</td>
      </tr>
     }
    </table>
    
    0 讨论(0)
  • 2020-12-07 17:40
    <add name="ConnectionString" providerName="MySql.Data.MySqlClient" connectionString="Data Source=127.0.0.1; port=3306; Initial Catalog=DbName; uid=root; pwd=*Password*;" />
    
    0 讨论(0)
提交回复
热议问题