Reputation: 15732
I use Visual Studio 2012 (Web Express) and I am creating a simple ASP.NET MVC application, (using the Database-First approach) by following this nice guide by hector espinosa. My problem is, that, for tables that use a composite primary key, the scaffolding system does not work correctly.
My table is as follows:
CREATE TABLE [dbo].[Unit](
[UnitOid] [int] NOT NULL,
/*other stuff*/
[ReplicationId] [int] NOT NULL,
CONSTRAINT [PK_Unit] PRIMARY KEY CLUSTERED
(
[UnitOid] ASC,
[ReplicationId] ASC
)
The scaffolding generates the controller and the view, but as soon as I click on an edit or details link, the only identifier used is the first (UnitOid
) value.
Example Action in the controller:
public ActionResult Details(int id = 0)
{
Unit unit = db.Units.Find(id); // throws an ArgumentException
if (unit == null)
{
return HttpNotFound();
}
return View(unit);
}
The exception message is quite clear:
"The number of primary key values passed must match the number of primary key values defined on the entity"
Is the scaffolding system of MVC4 / EF5 / VisualStudio 2012 really not able to handle that out of the box?
Note: This question is quite similar to this one. However, I am re-asking with reference to the current version of the tools.
Upvotes: 2
Views: 1141
Reputation: 31610
Since you have a composite key you need to provide both values. Note that Find takes param attributes so you can just do db.Units.Find(id, id2)
. If you have just one part of the key you will need to query the database and expect multiple results since there may be many entities in the database whose the part of key you are providing is the same.
Upvotes: 2