Asp MVC with MySQL Connection


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

Web.config

<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, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="DefaultConnection"
 providerName="MySql.Data.MySqlClient"
 connectionString="Data Source=localhost;port=3306;Initial Catalog=api_db;User Id=root;password=''"/>
</connectionStrings>

Model

MySqlCon 

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


CustomerModel

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

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

Views

@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>
Share on Google Plus

About Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment