ASP.NET MVC 4 EF5 with MySQL

前端 未结 3 846
半阙折子戏
半阙折子戏 2020-12-07 16:52

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

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

How do I tell my app th

3条回答
  •  无人及你
    2020-12-07 17:34

    Install Package:

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

    Web.config

    
     
    
    

    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 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
    
    
     @foreach (var item in Model)
     {
      
     }
    
    @Html.DisplayFor(modelItem => item.CustomerId) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Country)

提交回复
热议问题