using System.Data.Common;
using System.Data.Entity;
using MySql.Data.Entity;
namespace YourAppName.Models
{
public class MySqlContext : DbContext
{
public MySqlContext() : base(CreateConnection(), true)
{
}
private static DbConnection CreateConnection()
{
var connString = "your mysql connection string here";
var factory = new MySqlConnectionFactory();
return factory.CreateConnection(connString);
}
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourAppName.Models
{
[Table("YourTableName")]
public class DataModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
// Add more properties here as needed.
}
}
using System.Linq;
using System.Web.Mvc;
using YourAppName.Models;
namespace YourAppName.Controllers
{
public class MyController : Controller
{
private readonly MySqlContext db = new MySqlContext();
public ActionResult Index()
{
var dataModels = db.Set().ToList();
return View(dataModels);
}
}
}
@model IEnumerable
@foreach (var dataModel in Model)
{
@dataModel.Id - @dataModel.Name
}
通过以上步骤,您应该可以成功地在ASP.NET MVC应用程序中从MySQL数据库中获取数据并在视图中显示。