MVC4 – Entity Framework Code First

First of all, in Models folder, we create Data Context which will help us to connect to database

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

namespace MvcAuction.Models
{
    public class AuctionsDataContext: DbContext
    {
        public DbSet<Auction> Auctions { get; set; }

        /* This create new database from the scratch. Do not use in production *
        static AuctionsDataContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuctionsDataContext>());
        }
        */


    }
}

Web.config: we copy default connection string and modify new copy of connection string
1. Name: data context name – AuctionsDataContext
2. Name of mdf file – AuctionsDataContext.mdf
So in result our connection strings should look like this:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcAuction-20150301110555;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcAuction-20150301110555.mdf" providerName="System.Data.SqlClient" />
    <add name="MvcAuction.Models.AuctionsDataContext" connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MvcAuction.Models.AuctionsDataContext.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>

Auctions controller:

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

namespace MvcAuction.Controllers
{
    public class AuctionsController : Controller
    {
        //
        // GET: /Auctions/

        public ActionResult Index()
        {
            var db = new AuctionsDataContext();
            var auctions = db.Auctions.ToArray();

            return View(auctions);
        }

        public ActionResult Auction(long id)
        {
            var db = new AuctionsDataContext();
            var auction = db.Auctions.Find(id);

            return View(auction);
        }

        [HttpGet]
        public ActionResult Create()
        {
            var categoryList = new SelectList(new[] { "Automotive", "Electronics", "Games", "Home" });
            ViewBag.CategoryList = categoryList;
            return View();
        }

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "CurrentPrice")]Models.Auction auction)
        {
            if (ModelState.IsValid)
            {
                // Save to the database
                var db = new AuctionsDataContext();
                db.Auctions.Add(auction);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return Create();
        }
    }
}