Wednesday, December 23, 2015

MVC - Entity framework Database first approach

Earlier we saw how we can map our entities and Database using code first approach .
Here I have created a simple demo to show how already existing database table can be mapped to our model class entities


To do that , I created a table in MS SQL server 2012 called "Products"


Now , in visual studio project. Add new item(Ado.net entity data model) under model folder






Create a new SQL connection





Select the db objects like tables,views,sp.. whichever is relevant



Your designer class will be ready to show the entity diagram

Now you can see the database table schema is mapped to model classes. POCO classes are created automatically by entity framework along with context class


 


    public partial class Product


    {


        public string ProductId { get; set; }


        public string ProductName { get; set; }


        public Nullable<decimal> ProductCost { get; set; }


    }


Now add a controller and choose scaffolding template .



Controller action methods are as below


public class ProductController : Controller


    {


        private testdbEntities db = new testdbEntities();


 


        // GET: /Product/


        public ActionResult Index()


        {


            return View(db.Products.ToList());


        }


 


        // GET: /Product/Details/5


        public ActionResult Details(string id)


        {


            if (id == null)


            {


                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);


            }


            Product product = db.Products.Find(id);


            if (product == null)


            {


                return HttpNotFound();


            }


            return View(product);


        }


 


        // GET: /Product/Create


        public ActionResult Create()


        {


            return View();


        }


 


        // POST: /Product/Create


        // To protect from overposting attacks, please enable the specific properties you want to bind to, for


        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.


        [HttpPost]


        [ValidateAntiForgeryToken]


        public ActionResult Create([Bind(Include="ProductId,ProductName,ProductCost")] Product product)


        {


            if (ModelState.IsValid)


            {


                db.Products.Add(product);


                db.SaveChanges();


                return RedirectToAction("Index");


            }


 


            return View(product);


        }


 


        // GET: /Product/Edit/5


        public ActionResult Edit(string id)


        {


            if (id == null)


            {


                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);


            }


            Product product = db.Products.Find(id);


            if (product == null)


            {


                return HttpNotFound();


            }


            return View(product);


        }


 


        // POST: /Product/Edit/5


        // To protect from overposting attacks, please enable the specific properties you want to bind to, for


        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.


        [HttpPost]


        [ValidateAntiForgeryToken]


        public ActionResult Edit([Bind(Include="ProductId,ProductName,ProductCost")] Product product)


        {


            if (ModelState.IsValid)


            {


                db.Entry(product).State = EntityState.Modified;


                db.SaveChanges();


                return RedirectToAction("Index");


            }


            return View(product);


        }


 


        // GET: /Product/Delete/5


        public ActionResult Delete(string id)


        {


            if (id == null)


            {


                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);


            }


            Product product = db.Products.Find(id);


            if (product == null)


            {


                return HttpNotFound();


            }


            return View(product);


        }


 


        // POST: /Product/Delete/5


        [HttpPost, ActionName("Delete")]


        [ValidateAntiForgeryToken]


        public ActionResult DeleteConfirmed(string id)


        {


            Product product = db.Products.Find(id);


            db.Products.Remove(product);


            db.SaveChanges();


            return RedirectToAction("Index");


        }


 


        protected override void Dispose(bool disposing)


        {


            if (disposing)


            {


                db.Dispose();


            }


            base.Dispose(disposing);


        }


    }




Views are automatically created . build the solution and run it.

you can do CRUD operations .
I have added an item using create new link on the UI
and same is reflected in the DB

Monday, December 14, 2015

Swagger UI for WebAPi

 Swagger is yet another powerful API documentation tool .Microsoft has come up with easy integration methodology with WebAPi


It specifies the format (URL, method, and representation) to describe REST web services.


Earlier I used to use Fiddler for the same purpose. to do CRUD operations. using WEBAPI
or other alternative was to install RESTclient addon for firefox .
now Swagger UI provides more cleaner and efficient interactive API console for people to quickly learn about and try the API.


Now to do this you need to add references to your ASP.Net WebApi solution called SwashBuckle
from Nugets PM


now create your Model class as usual


public class Questions





{


[Key]

public int QuestionId { get; set; }

public string QuestionName { get; set; }












}



scaffold your controllers
public class QuestionController : ApiController





{


private QuestionContext db = new QuestionContext();

// GET api/Question


public IQueryable<Questions> GetQuestions()






{


return db.Questions;






}



}
now run the solution .
append swagger  word to the url http://localhost:49775/swagger/
you will find Swagger UI

below is the example of GET by id method using Swagger