ASP。netmvc 4 EF5和MySQL

时间:2022-06-01 12:48:09

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

我刚买了VS2012,我想开始一个ASP。netmvc 4应用与EF5。

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

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

How do I tell my app that it should use MySQL? (I either want to use the devart MySQL connector or the one from mysql.com)

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

3 个解决方案

#1


26  

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.

您需要使用连接字符串、DbProviderFactory和一个用于MySql连接器6.5.4的自定义数据库初始化器来设置配置。我已经详细介绍了使EF5和MySql发挥作用的全部步骤,包括我博客上的初始化器代码。如果你需要ASP。Net会员提供商解决方案:ASP。MySQL的会员/角色提供者?我将在这里发布完整的EF5 MySql解决方案。

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.

MySql连接器目前不支持EF 5迁移和ASP。NET只支持MS SQL上的simplembership (MVC4缺省值),而不支持MySql。下面的解决方案是代码优先。

The steps are:

的步骤是:

  1. Grab EF 5 from NuGet
  2. 从NuGet上获取EF 5
  3. Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4)
  4. 抓住MySql。数据和MySql.Data。来自NuGet(6.5.4)或MySql(6.6.4)的实体
  5. Configure a MySql Data Provider
  6. 配置MySql数据提供程序
  7. Configure a MySql Connection String
  8. 配置MySql连接字符串
  9. Create a Custom MySql Database Initializer
  10. 创建一个自定义MySql数据库初始化器
  11. Configure the Custom MySql Database Initializer
  12. 配置自定义MySql数据库初始化器
  13. Configure ASP.NET membership if you require it
  14. 配置ASP。如果您需要,请提供净会员资格

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/

如果您正在使用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/

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:

使AccountController和Views工作:

  1. Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view
  2. 删除MVC 4 AccountController、accountmodel、Account视图文件夹和_LoginPartial共享视图
  3. Create a new MVC 3 web application
  4. 创建一个新的MVC 3 web应用程序
  5. Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application
  6. 将MVC 3 AccountController、accountmodel、Account视图文件夹和_LogOnPartial共享视图复制到MVC 4应用程序中
  7. Replace @Html.Partial(“_LoginPartial”) in the shared _Layout view with @Html.Partial(“_LogOnPartial”)
  8. 将共享_Layout视图中的@Html.Partial(“_LoginPartial”)替换为@Html.Partial(“_LogOnPartial”)

#2


1  

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

#3


0  

Install Package:

安装包:

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

Web.config

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

#1


26  

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.

您需要使用连接字符串、DbProviderFactory和一个用于MySql连接器6.5.4的自定义数据库初始化器来设置配置。我已经详细介绍了使EF5和MySql发挥作用的全部步骤,包括我博客上的初始化器代码。如果你需要ASP。Net会员提供商解决方案:ASP。MySQL的会员/角色提供者?我将在这里发布完整的EF5 MySql解决方案。

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.

MySql连接器目前不支持EF 5迁移和ASP。NET只支持MS SQL上的simplembership (MVC4缺省值),而不支持MySql。下面的解决方案是代码优先。

The steps are:

的步骤是:

  1. Grab EF 5 from NuGet
  2. 从NuGet上获取EF 5
  3. Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4)
  4. 抓住MySql。数据和MySql.Data。来自NuGet(6.5.4)或MySql(6.6.4)的实体
  5. Configure a MySql Data Provider
  6. 配置MySql数据提供程序
  7. Configure a MySql Connection String
  8. 配置MySql连接字符串
  9. Create a Custom MySql Database Initializer
  10. 创建一个自定义MySql数据库初始化器
  11. Configure the Custom MySql Database Initializer
  12. 配置自定义MySql数据库初始化器
  13. Configure ASP.NET membership if you require it
  14. 配置ASP。如果您需要,请提供净会员资格

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/

如果您正在使用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/

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:

使AccountController和Views工作:

  1. Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view
  2. 删除MVC 4 AccountController、accountmodel、Account视图文件夹和_LoginPartial共享视图
  3. Create a new MVC 3 web application
  4. 创建一个新的MVC 3 web应用程序
  5. Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application
  6. 将MVC 3 AccountController、accountmodel、Account视图文件夹和_LogOnPartial共享视图复制到MVC 4应用程序中
  7. Replace @Html.Partial(“_LoginPartial”) in the shared _Layout view with @Html.Partial(“_LogOnPartial”)
  8. 将共享_Layout视图中的@Html.Partial(“_LoginPartial”)替换为@Html.Partial(“_LogOnPartial”)

#2


1  

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

#3


0  

Install Package:

安装包:

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

Web.config

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