The number of primary key values passed must match number of primary key values defined on the entity

Ørjan picture Ørjan · Nov 26, 2014 · Viewed 23.1k times · Source

I've created a view in SQL Server that contains the most important columns from different tables. Printing the content of the table to the ASP.NET MVC view works fine, but when I want to get the details of a single record the problem occur.

The number of primary key values passed must match number of primary key values defined on the entity.

I navigate to the specific record doing this:

@Html.ActionLink("Details", "Details", new {  id=item.Record_number  })

Record number is the primary key. I set this manually by right clicking on the specific variable in the .edmx model. Then I try to get the specific data using the following:

    //
    // GET: /Record/Details/5
    public ActionResult Details(int id = 0)
    {
        try
        {
            RecordDataView record = db.RecordDataView.Find(id); //HERE THE ERROR OCCUR
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        catch(EntityException)
        {
            return RedirectToAction("NoDatabaseConnection", "Home");
        }
    }

And the model look like this:

namespace Implant.Database
{
    using System;
    using System.Collections.Generic;

    public partial class RecordDataView
    {
        public int Record_number { get; set; }
        public Nullable<System.DateTime> DOB { get; set; }
        public Nullable<System.DateTime> Record_date { get; set; }

        /** rest of code omitted */ 
    }
}

At the moment I am using the following code to make it all work. But I don't feel this is a very good way or efficient. And I am very curious how to fix the failure above!

    //
    // GET: /Record/Details/5
    public ActionResult Details(int id = 0)
    {
        var record = from r in db.RecordDataView
                     select r;
        if (id != 0)
        {
            record = record.Where(r => r.Record_number == id);
        }
        RecordDataView rec = record.ToList().First(); 

        return View(rec);   
    }

Someone got any idea why this error occurs? Thanks for help!

Answer

Marcin picture Marcin · Nov 26, 2014

If you set your Primary Key in .edmx you should update your database too, because you have PK in your model and not in your database. Update: does not work for views.

For views use .SingleOrDefault instead of Find().

In this scenario change the following line: RecordDataView record = db.RecordDataView.Find(id); To the following: RecordDataView recorddataview = db.RecordDataView.SingleOrDefault(m => m.Record_number == id);