MVC3 / Razor Add Controller "Get-PrimaryKey" cannot find primary key

I created an Entity Framework model based on an existing database. Entity Framework uses the DbContext ADO.NET generator.

I also created an MVC3 / Razor project that uses the DLLs from the first project. When I click on the β€œAdd β†’ Controller” option 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 Groups.cs that Visual Studio generated and add "using System.ComponentModel.DataAnnotations;" and then add [Key] in the declaration of the Groups field. However, this is the generated code. If I recompile the Entity Framework project, my changes will of course be lost.

So - My question is:

I am doing something wrong, because of which Visual Studio cannot understand what the Key field is, or is it just an error with the forest code, which prevents it from understanding what the key is.

I should mention that this only fails with string key keys. If the field was declared as a whole, then everything works fine.

Here is a lookup 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 is My Environment:

Visual Studio 2010 Entity Framework 4.1 MVC 3 SQL Server 2008 Service Pack 3 (SP3)
+6
source share
2 answers

I believe that MVC Scaffolding, as a convention, expects the primary key to have an β€œId” in the property 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 when I need to change the group_name, I would not have to handle the problems that would arise.

+1
source

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

The second parameter is Group_name by adding/decorating [Key] attribute above the field.

+1
source

Source: https://habr.com/ru/post/902062/


All Articles