How do I execute a SQL query with ASP MVC5 + Entity?
To create the MVC I used the entity's own option (I created the model, context) and already generated the controller and the views
Follow the controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace TeZ.Models
{
public class MembersController : Controller
{
private MembersContext db = new MembersContext();
// GET: Members
public ActionResult Index()
{
return View(db.members.ToList());
}
// GET: Members/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
// GET: Members/Create
public ActionResult Create()
{
return View();
}
// POST: Members/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "mbMatricula,mbName,mbFunc,mbMail,mbPic,mbPass,mbActive")] Member member)
{
if (ModelState.IsValid)
{
db.members.Add(member);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(member);
}
// GET: Members/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
// POST: Members/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "mbMatricula,mbName,mbFunc,mbMail,mbPic,mbPass,mbActive")] Member member)
{
if (ModelState.IsValid)
{
db.Entry(member).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(member);
}
// GET: Members/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
// POST: Members/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Member member = db.members.Find(id);
db.members.Remove(member);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}