带有MySQL的ASP.NET MVC 4 EF5

时间:2012-08-29 15:29:26

标签: mysql asp.net-mvc entity-framework

所以我刚拿起VS2012,我想用EF5启动一个ASP.NET MVC 4应用程序。

我的主机没有MSSQL所以我必须使用MySQL。

如何告诉我的应用它应该使用MySQL? (我要么使用devart MySQL连接器,要么使用mysql.com中的连接器)

3 个答案:

答案 0 :(得分:26)

您需要使用连接字符串DbProviderFactory和MySql Connector 6.5.4的自定义DatabaseInitializer设置配置。我详细介绍了full step for getting EF5 and MySql to play, including code for the initializers on my blog。如果您需要ASP.Net成员资格提供商解决方案,之前已经问过:ASP.NET Membership/Role providers for MySQL?我将在此处发布解决方案,以获得完整的EF5 MySql解决方案。

MySql连接器当前不支持EF 5迁移,ASP.NET仅支持MS SQL上的SimpleMembership(默认为MVC4)而不支持MySql。以下解决方案适用于Code First。

步骤如下:

  1. 从NuGet
  2. 获取EF 5
  3. 从NuGet(6.5.4)或MySql(6.6.4)获取MySql.Data和MySql.Data.Entity
  4. 配置MySql数据提供程序
  5. 配置MySql连接字符串
  6. 创建自定义MySql数据库初始化程序
  7. 配置自定义MySql数据库初始化程序
  8. 如果需要,请配置ASP.NET成员资格
  9. 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>
    

    连接字符串

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

    数据库初始化程序

    如果您正在使用NuGet(6.5.4)中的MySql连接器,则需要自定义初始化程序。代码http://brice-lambson.blogspot.se/2012/05/using-entity-framework-code-first-with.html 或在http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/

    然后将其添加到配置

    <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 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>
    

    获取AccountController和Views工作:

    1. 删除MVC 4 AccountController,AccountModels,帐户视图文件夹和_LoginPartial共享视图
    2. 创建新的MVC 3 Web应用程序
    3. 将MVC 3 AccountController,AccountModels,Account视图文件夹和_LogOnPartial共享视图复制到MVC 4应用程序中
    4. 使用@Html.Partial(“_LoginPartial”)
    5. 替换共享_Layout视图中的@Html.Partial(“_LogOnPartial”)

答案 1 :(得分:1)

<add name="ConnectionString" providerName="MySql.Data.MySqlClient" connectionString="Data Source=127.0.0.1; port=3306; Initial Catalog=DbName; uid=root; pwd=*Password*;" />

答案 2 :(得分:0)

  

安装包:

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>
  

创建模型类

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; }
    }
}
  

创建模型上下文:

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; }
    }
}
  

创建控制器类

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());
        }
 }
}
  

代码添加视图页面:

@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>