Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3/Razor Add Controller "Get-PrimaryKey" is failing to find the Primary Key

I've created an Entity Framework Model based on an existing database. The Entity Framework is using the ADO.NET DbContext Generator.

I've also created a MVC3/Razor project that is using the DLL from the first project. When I click on the option "Add -> Controller" and fill out the required fields I get an annoying error:

Scaffolding GroupController...
EMR_MasterEntities already has a member called 'Groups'. Skipping...
Get-PrimaryKey : Cannot find primary key property for type 'CHS.CCC.DataModel.Group'. No properties appear to be primar
y keys.
At C:\Users\adriangilbert\Desktop\CHS.Monitor\packages\MvcScaffolding.1.0.6\tools\Controller\MvcScaffolding.Controller.
ps1:74 char:29
+ $primaryKey = Get-PrimaryKey <<<<  $foundModelType.FullName -Project $Project -ErrorIfNotFound
    + CategoryInfo          : NotSpecified: (:) [Get-PrimaryKey], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.GetPrimaryKeyCmdlet

To get around this, I need to go to the Groups.cs that was generated by Visual Studio and add 'using System.ComponentModel.DataAnnotations;' and then add [Key] to the declaration the Groups field. However this is generated code. If I recompile the Entity Framework Project, my changes will of course be lost.

So - My question is:

Am I doing something wrong that is causing Visual Studio to not be able to figure out what the Key field is, or is this just a bug with the Scaffolding Code that is preventing it from figuring out that the Key is.

I should mention that this only fails with string-based Primary Keys. If the field had been declared as an Integer, then everything works perfectly.

Here is the problematic table:

CREATE TABLE [dbo].[Groups](
    [group_name] [varchar](45) NOT NULL,
    [dbname] [varchar](45) NOT NULL,
    [user] [varchar](45) NULL,
    [CompatibilityVersion] [nvarchar](20) NULL,
    ...

PRIMARY KEY CLUSTERED  ([group_name] ASC)
) ON [PRIMARY]

Here's My Environment:

  • Visual Studio 2010
  • Entity Framework 4.1
  • MVC 3
  • SQL Server 2008 with SP3
  • like image 205
    Adrian Avatar asked Nov 21 '11 21:11

    Adrian


    2 Answers

    I believe that MVC Scaffolding, as a convention, expects that the primary key has "Id" on the property's name, but I'm not sure.
    If possible, in your case I would create a surrogate key to use as the primary key for the table, so that when the group_name needs to be changed, I would not have to handle the issues that would arise.

    like image 116
    Nelson Reis Avatar answered Sep 17 '22 19:09

    Nelson Reis


    By default EF considers property as PrimaryKey, only if it is in format of ID or {TableName}ID...in your case it should be GroupNameId or Id.

    The second options is Group_name by adding/decorating [Key] Attribute above the field.

    like image 20
    Brad Avatar answered Sep 18 '22 19:09

    Brad