带有 MySQL 的 ASP.NET MVC 4 EF5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12181428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 4 EF5 with MySQL
提问by kasperhj
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? (I either want to use the devart MySQL connector or the one from mysql.com)
我如何告诉我的应用程序它应该使用 MySQL?(我想使用 devar MySQL 连接器或来自 mysql.com 的连接器)
回答by agilejoshua
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 Connector 6.5.4 的自定义 DatabaseInitializer 设置您的配置。我已经详细介绍了让 EF5 和 MySql 发挥作用的完整步骤,包括我博客上的初始化程序代码。如果您需要 ASP.Net 成员资格提供程序解决方案,之前有人问过:MySQL 的 ASP.NET 成员资格/角色提供程序?我也会在这里发布一个完整的 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 上的 SimpleMembership(MVC4 默认),而不支持 MySql。下面的解决方案适用于 Code First。
The steps are:
步骤是:
- Grab EF 5 from NuGet
- Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4)
- Configure a MySql Data Provider
- Configure a MySql Connection String
- Create a Custom MySql Database Initializer
- Configure the Custom MySql Database Initializer
- Configure ASP.NET membership if you require it
- 从 NuGet 获取 EF 5
- 从 NuGet (6.5.4) 或 MySql (6.6.4) 获取 MySql.Data 和 MySql.Data.Entity
- 配置一个 MySql 数据提供者
- 配置一个 MySql 连接字符串
- 创建自定义 MySql 数据库初始化程序
- 配置自定义 MySql 数据库初始化程序
- 如果需要,配置 ASP.NET 成员资格
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.htmlor 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
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 工作:
- Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view
- Create a new MVC 3 web application
- Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application
- Replace
@Html.Partial(“_LoginPartial”)
in the shared _Layout view with@Html.Partial(“_LogOnPartial”)
- 删除MVC 4 AccountController、AccountModels、Account 视图文件夹和_LoginPartial 共享视图
- 创建一个新的 MVC 3 Web 应用程序
- 将 MVC 3 AccountController、AccountModels、Account 视图文件夹和 _LogOnPartial 共享视图复制到您的 MVC 4 应用程序中
@Html.Partial(“_LoginPartial”)
在共享 _Layout 视图中替换为@Html.Partial(“_LogOnPartial”)
回答by Neha Katoch
<add name="ConnectionString" providerName="MySql.Data.MySqlClient" connectionString="Data Source=127.0.0.1; port=3306; Initial Catalog=DbName; uid=root; pwd=*Password*;" />
回答by Ram Pukar
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>