Thursday, 21 March 2013

MVC 4 - Simple CRUD (Entity Framework) example with composite primary key PART 2

Part one of this tutorial can be found here
http://howtodomssqlcsharpexcelaccess.blogspot.ca/2013/03/mvc-4-simple-crud-entity-framework.html

We will have to edit the following code:


We will pass our composite primary key to edit, details and delete functions
        @Html.ActionLink("Edit", "Edit", new { Styleid=item.style_id, ColorId = item.colour_id }) |
            @Html.ActionLink("Details", "Details", new {Styleid=item.style_id, ColorId = item.colour_id}) |
            @Html.ActionLink("Delete", "Delete", new { Styleid=item.style_id, ColorId = item.colour_id })


 Modify TestController methods - ensure they are receiving StyleId and ColorId
For instance Edit method will look like this

        public ActionResult Edit(int StyleId = 0, int ColorId = 0)
        {
            TestCompositePrimary testcompositeprimary = db.TestCompositePrimaries.Find(StyleId,ColorId);
            if (testcompositeprimary == null)
            {
                return HttpNotFound();
            }
            ViewBag.colour_id = new SelectList(db.ColorMasters, "ColourId", "ColourName", testcompositeprimary.colour_id);
            ViewBag.style_id = new SelectList(db.StyleMasters, "StyleId", "StyleName", testcompositeprimary.style_id);
            return View(testcompositeprimary);
        }
 Run the program - go to http://localhost:50566/Test and try to edit or delete some records - this time it will work perfectly.

Part 1 of this tutorial can be found here
http://howtodomssqlcsharpexcelaccess.blogspot.ca/2013/03/mvc-4-simple-crud-entity-framework.html

4 comments:

  1. Thanks lot
    Saved me a lot of my time

    ReplyDelete
  2. Thanks for the tutorial.
    I have a similar database but the key is composed by 4 variables (2 of them are foreign keys) and all of them are strings.
    I followed your example step by step but it's not working. Any idea why that might be? Is it because they're strings?

    ReplyDelete
  3. TestCompositePrimary testcompositeprimary = db.TestCompositePrimaries.Find(StyleId,ColorId);

    Can not find "Find", any idea why?

    ReplyDelete