简体   繁体   English

带有MySQL的ASP.NET MVC 4 EF5

[英]ASP.NET MVC 4 EF5 with MySQL

So I've just picked up VS2012 and I want to start an ASP.NET MVC 4 app with EF5. 所以我刚拿起VS2012,我想用EF5启动一个ASP.NET MVC 4应用程序。

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? 如何告诉我的应用程序它应该使用MySQL? (I either want to use the devart MySQL connector or the one from mysql.com) (我要么使用devart MySQL连接器,要么使用mysql.com中的连接器)

You need to setup your config with a connection string, DbProviderFactory and a custom DatabaseInitializer for MySql Connector 6.5.4. 您需要使用连接字符串DbProviderFactory和MySql Connector 6.5.4的自定义DatabaseInitializer设置配置。 I have detailed the full step for getting EF5 and MySql to play, including code for the initializers on my blog . 我详细介绍了使用EF5和MySql完整步骤,包括我博客上初始化程序的代码 If you require ASP.Net membership provider solution it been asked before: ASP.NET Membership/Role providers for MySQL? 如果您需要ASP.Net成员资格提供程序解决方案之前曾被问过: ASP.NET的成员身份/角色提供程序? I will post the solution here also for a complete EF5 MySql solution. 我将在此处发布解决方案,以获得完整的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. MySql连接器当前不支持EF 5迁移,ASP.NET仅支持MS SQL上的SimpleMembership(默认为MVC4)而不支持MySql。 The solution below is for Code First. 以下解决方案适用于Code First。

The steps are: 步骤是:

  1. Grab EF 5 from NuGet 从NuGet获取EF 5
  2. Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4) 从NuGet(6.5.4)或MySql(6.6.4)获取MySql.Data和MySql.Data.Entity
  3. Configure a MySql Data Provider 配置MySql数据提供程序
  4. Configure a MySql Connection String 配置MySql连接字符串
  5. Create a Custom MySql Database Initializer 创建自定义MySql数据库初始化程序
  6. Configure the Custom MySql Database Initializer 配置自定义MySql数据库初始化程序
  7. Configure ASP.NET membership if you require it 如果需要,请配置ASP.NET成员身份

DbProvider 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. 如果您正在使用NuGet(6.5.4)中的MySql连接器,则需要自定义初始化程序。 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/ 代码见http://brice-lambson.blogspot.se/2012/05/using-entity-framework-code-first-with.htmlhttp://www.nsilverbullet.net/2012/11/07/ 6步对得到实体框架-5-劳动与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 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>

Get the AccountController and Views working: 获取AccountController和Views工作:

  1. Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view 删除MVC 4 AccountController,AccountModels,Account视图文件夹和_LoginPartial共享视图
  2. Create a new MVC 3 web application 创建一个新的MVC 3 Web应用程序
  3. Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application 将MVC 3 AccountController,AccountModels,Account视图文件夹和_LogOnPartial共享视图复制到MVC 4应用程序中
  4. Replace @Html.Partial(“_LoginPartial”) in the shared _Layout view with @Html.Partial(“_LogOnPartial”) @Html.Partial(“_LoginPartial”)替换共享_Layout视图中的@Html.Partial(“_LogOnPartial”)
<add name="ConnectionString" providerName="MySql.Data.MySqlClient" connectionString="Data Source=127.0.0.1; port=3306; Initial Catalog=DbName; uid=root; pwd=*Password*;" />

Install Package: 安装包:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM