MVC3/Razor Add Controller "Get-PrimaryKey" is failing to find the Primary Key - asp.net-mvc-3

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

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.

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.

Related

entity framework without primary key

I have created an entity class for my mvc application. But, my table doesn't have a primary key and the VS throws back an error:
"The table/view does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view."
Is there a way to still use the model even if it has no primary key??
or Do I have to add a pk? or should I just use execute command?
Any suggestion/comment is highly appreciated. Thanks in advance. :)

Changing one table in EDMX file affect all actions at project. The schema is not valid

We are using VS2010 and MVC 3.
This project was working fine. With over 40 tables in EDMX Model. We change a one table over EDMX file and then nothing work.
All actions (related or not with change) gives this error:
The scheme is not valid. Errors:
The type has no key member. Both RelationshipType as EntityType must
have members with BaseType key or key members. The type has no key
member. Both RelationshipType as EntityType must have members with
BaseType key or key members.
Description: An unhandled exception when running the current Web
request. Check the stack trace for more information about the error
and where it originated in the code.
All tables has a key...
We are restoring a old backup, and working fine... rebuild and then nothing work. !!!
Any idea, thank you in advance...
For example: (this is a piece of Modelo.designer.cs)
public ObjectSet Clientes {
get
{
if ((_Clientes == null))
{
_Clientes = base.CreateObjectSet("Clientes"); // ERROR HERE
}
return _Clientes;
}
}
Same error for all tables in the Model (EDMX). We are rebuild Model.designer.cs using right mouse menu option "execute custom tool"
We deleted old Model, create a new and... the same error.
Change EDMX model and then do update model from database -> refresh -> table

Spring Roo Web MVC Insert - No Default Primary Key

I have a web MVC project generated by Spring roo. I reverse engineered a MSSQL DB and have the need to create my own primary keys but am unable to insert using the inputs Roo generated (anticipates an auto increment or self-generated ID). Any ideas? I recieve the below message from the console when I attempt this.
ERROR org.hibernate.util.JDBCExceptionReporter - Field 'id' doesn't have a default value
It appears that the DBRE code generation for #ManyToOne/#JoinColumn is a bit incorrect. The code generator incorrectly sets such a field with "insertable = false" which then omits this particular foreign key column reference during an insert into the referencing table. Change it to "insertable = true" as well as the "updateable" if you require and you should be good.

entity framework returning only one value but the list size is correct

Entity framework returning only one value but the list size is correct
I have a table that does not have primary id and I need to get or select all the values in it.
What I see is when I do the selection with linq the number of objects is correct but it is the first row over and over.
I am simply doing something like this
List<MyValueType> valuesInDB = myDb.MyValueTypes.ToList();
Problem is I may get thousands of rows (which is correct) but the rows all have the same exact data.
I am using VS 2010 and used the wizard to create my EF object.
The problem is that entity framework is not able to work with entity without a key. So if your table doesn't specify a key, entity framework will infer its own. The key created by EF is composed of all non-nullable non-binary columns.
So if you for example have single non-nullable column in your entity which have only very small set of values (like enum) you will be able to load only single entity "per value". The reason is an inner implementation of the context and the state manager which uses Identity map pattern. When data record is retrieved from database, EF will first check an entity key and tries to find an object with the same key in its internal storage. If an object is found it will use that object instead of data record retrieved (despite of different data). If an object with the key is not found a new object is materialized and added to internal storage.
That is the purpose of Identity map - object with given key should be created only once by each context. Identity map is core pattern in ORM.
I wrote about Identity map also in this question.
I would suggest searching for the word "Warning" in your EDM's designer.cs file. It might tell you if Entity Framework is having any issues with your table.
I really can't comment much in the absence of the table design. I tried replicating your problem but wasn't able to do so. Here is what I did:
Created a table with no primary key but it had a unique key on an ID column. Entity Framework was able to infer a primary key and when I fetched the data, I not only got the correct number of rows but also the corrects data in those rows.
Created a table with no primary key and no unique key. Also there was no column called ID. Entity Framework excluded this table in the EDM that was generated. Consequently I wasn't able to query this table at all.This was displayed as a warning in the EDM designer file.
It would be better if you can share the create script for your table.

Implementing identifying relationships with EF4

I'm currently in a situation where I need to delete entities without having access to the associated ObjectContext. I read about identifying relationships and they seem to be exactly what I need: I want to delete an object, once it is no longer referenced by its "parent" object.
I am using Visual Studio 2010 Premium to generate my database from an edmx file. As far as I understand, I need to include the foreign key of my "parent" object in the primary key of my "child" object table. However, I cannot find a way to tell Visual Studio to do this.
Can someone please help me out on this? Am I completely on a wrong path or am I just missing a setting somewhere?
I finally figured it out:
Go to your Child entity and create a scalar property ParentId. Set this property as entity key (making it a primary key, together with your Id property of your Child entity). Next go to your ParentChild relationship and add a referential constraint. Principal for the constraint is your Parent and Dependant is your Child. Dependant property must be the property you just created on your Child (i.e. ParentId). Save everything and you're good to go.
Basically this is described as "scenario 2" in this blog post: http://mocella.blogspot.com/2010/01/entity-framework-v4-object-graph.html
No, you are in the right path. What you need to do is in the EDM designer, after creating your 2 entities (Parent and Child), right click on the Parent Entity and select Add => Association... and then specify Multiplicity and Navigation property names, and click Ok. You'll see that VS create an association in between which will result on a relationship between these 2 table later on when you generate a database from your model.
Do not create a property like ParentID on your Child entity as it will be automatically created by the designer once you create the association.
Furthermore, you can right click on the association in the EDM designer and Select Properties and Select "Cascade" on "End2 OnDelete" option so that the child will be deleted when the parent is deleted.

Resources