MVC3 – Error setting up Controller with Entity framework

asp.net-mvc-3entity-framework-4

The steps I go through…

  • Add new ADO.NET Entity Data Model > Generate from DB > Setup new connection string to adventureworks db > Next > Select table "DatabaseLog" > Finish. Verify DatabaseLog is visible in the edmx view.

  • Right click controller > Add controller

  • Template
    Controller with read/write actions and views, using Entity

  • Model class
    AdventureWorksDWEntities

  • Context
    New data Context > Accept default name

  • View
    Razor

  • Click Add.

Produce Error:
"Unable to retrieve metadata for 'DatabaseDocumentor.models.AdventureWorksDWEntities'.

  • System.Data.Edm.EdmEntityeType: EntityType 'AdventureWorksDWEntities' has no key defined. Define the key for this entitytype.

  • System.Data.Edm.EdmEntitySet: EntityType: EntitySet 'AdventureWorksDWEntities' is based on type 'AdventureWorksDWEntities' that has no keys defined.


I tried again using AdventureWorks (not AdventureWorksDW) and this time it worked. But, I still don't understand what to pick when generating a controller. I have 3 options:

Template
Here I picked Controller with read/write actions and views, using Entity. This is easy enough to understand. I want to have my tables generated for me so I pick this option.

Model
This is what I want to model. In this case I want to model the "Department" table. So I choose Department.

Context
This one is real fuzzy to me. I chose *Name*Entities. This is the value in the web.config connection strings area. Why do I need to choose my connection string as the context? I only know context as "an object that I use to get to my entities" in C#. So, here it's hard for me to visualize. Do I need to always choose my connection string for the context?

Best Answer

This issue can occur when the Context is not correctly chosen from the dropdown. The context should be the value stored in the web.config

<add name="NamedEntitiesCs1"

that also contains the Model you want to generate.