gpt4 book ai didi

c# - 将 MySql 与 ASP.NET MVC( Entity Framework 6)结合使用

转载 作者:行者123 更新时间:2023-11-29 06:32:45 55 4
gpt4 key购买 nike

我的数据库最初是用 MSSQL 构建的,但最近我将其迁移到了 MySql。但是,现在我需要将它连接到我的 MVC 项目(现有)。我尝试使用 Entity Framework 向导执行此操作,但收到以下错误消息。

Error message

我继续阅读,发现我需要一些 MySql 需要的类才能与 Visual Studio 一起工作,并添加了以下 NuGet 包。我什至安装了 MySql Microsoft 软件包(带有连接器 + MySql for Visual Studio)。

NuGet packages

即使安装了所有软件包,我仍然收到此错误消息。如何将我现有的 MVC 项目连接到 MySql 数据库?

最佳答案

First install three Package Manager Console one by one (Tools->NutGet Package Manger->Package Manger Console)

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>

Models DbContext

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

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

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

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>

关于c# - 将 MySql 与 ASP.NET MVC( Entity Framework 6)结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901410/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com