Asp MVC with PosgreSql Connection


> Install-Package Npgsql
> Install-Package Npgsql -Version 2.2.0
> Install-Package EntityFramework

Web.config

<connectionStrings>
<add name="DefaultConnectionString" connectionString="server=localhost;user id=postgres;password=admin;database=api_db" providerName="Npgsql" />
</connectionStrings>
<system.data>
<DbProviderFactories>
 <add name="Npgsql Data Provider"
  invariant="Npgsql"
  support="FF"
  description=".Net Framework Data Provider for Postgresql"
  type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>

Model

PGDbContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace PgDemo.Models
{
    public class PGDbContext: DbContext
    {
        public PGDbContext() : base(nameOrConnectionString: "DefaultConnectionString") { }
        public virtual DbSet<Users> Usr { get; set; }
    }
}

Users

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace PgDemo.Models
{
    [Table("users", Schema = "public")]
    public class Users
    {
        [Key]
        public int id { get; set; }
        public string username { get; set; }
        public string userpass { get; set; }
    }
}

Controller

using PgDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PgDemo.Controllers
{
    public class HomeController : Controller
    {
        PGDbContext _context;
        public HomeController()
        {
            _context = new PGDbContext();
        }
        public ActionResult Index()
        {
            return View(_context.Usr.ToList());
        }
}
}

Views

@using PgDemo.Models
@model IEnumerable<Users>
<table border="1">
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.id)</td>
<td>
@Html.DisplayFor(modelItem => item.username)
</td>
<td>@Html.DisplayFor(modelItem => item.userpass)</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