EF 4.1 Database first. "EntityType <Entity> has no key defined." - entity-framework-4

I have created a VS 2010, .Net 4, MVC 4 application with Entity Framework 4.1 and MS SQL Server 2008.
The application is split into an MVC web project, a services project and a number of entities projects. Each entity project contains an edmx file and a context. The edmx files have been generated from the database, not code first.
My application compiles and runs successfully until I access a page which references one specific edmx file then I get the errors:
System.Data.Edm.EdmEntityType: : EntityType '<Entity>' has no key defined. Define the key for this EntityType.
and
System.Data.Edm.EdmEntitySet: EntityType: EntitySet <Entity>s is based on type <Entity> that has no keys defined.
The edmx contains 22 tables and I get this message for 8 of them.
The tables all contain primary keys in the database and these appear to have been brought through to the edmx as the edmx shows the key symbol by the correct fields and if you view the properties of the fields Entity Key = True. All of the other entity projects work correctly and some of them contain some of the same tables that are causing problems here.
I have deleted some of the offending tables and re-added them, but this didn't help. I am loathed to delete the whole edmx and start again, as it took quite a while to get right and this might not fix the problem.
Can anybody help me with this problem please? Thank you.

Let's assume a property Id maps to your primary key, then you have to decorate its property with [key] attribute like this:
[Key]
public int Id { get; set; }

Related

ASP.NET Identity 2.0 DB First Approach: Adding new Columns

I am trying to use ASP.NET Identity 2.0 with existing database.
I have created an MVC project (which uses Individual Account Authentication), then I registered for a use in order to create the DB.
Then:
I created scripts for the necessary tables and added them to my own DB
I added ADO.NET Entity Data Model (database first) which include my tables plus identity tables.
I ran the application and registered for a user, everything is going fine.
Now, I need to add a relation to AspNetUser table.
I added the Column LocationId with the relationship in DB.
I Added the following to the Application User Class:
public virtual Region Region { get; set; }
Then, I updated my Model and run the application, when I tried to register for new user, I got the following error:
AspNet UserLogin: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNet UserLogin' that has no keys defined.
How is it possible to continue using DB First Approach in this scenario?
Identity uses Code First approach for making Identity System make customization as more as possible and you are using DB first approach for your common data access. So there are 2 contexts, one is for your data and other is for you Identity. You need to write Identity classes and make a code first migration of Identity context class by typing in the Package Manager Console as:
`Enable-Migrations -ContextNameType [Your_Identity_Context]
This will enable code first migrations just for your Identity context type. If you want to add region property in your user table, then in 'ApplicationUser' (or any class derived from IdentityUser) add the required region property and then apply the migrations to update the user table in the database.
Generating SQL script and applying to the database is not a good approach.

ASP.NET MVC Model First Many To Many

I have some problems working with model first many to many relationship. Since I created many-many relationship between Town and Author via interface builder it created table TownAuthor with keys Towns_TownID and Authors_AuthorID but I want that just to be called TownID and AuthorID, how do I change that?
In Code first I would use that modelBuilder configuration in Context but I have no idea how to do this via model first...
You have to change the names of these columns in the Entity Designer DDL script (which is generated from the EDMX file and has ModelName.edmx.sql name) before executing it.
-- Creating table 'TownAuthor'
CREATE TABLE [dbo].[TownAuthor] (
[TownID] int NOT NULL,
[AuthorID] int NOT NULL
);
GO

how to manage two EDMX files incase they have the same table name

I am working on an asp.net mvc web application,. i use the entity framework ADO.net entity data module to map two different databases and i have created two EDMX files. but unfortunately these databases have two tables with the same name UserGroup & Router. so i am unable to map these two tables inside the EDMX files, as entity framework will automatically delete the existing table which have the same name.
can any one advice how i can fix this , without having to rename the tables ?
You may change the name of the table on designer. Click the entity on designer and click and change the name property. Or you may have these two edmx in different name spaces (If it is possible)
Each EDMX file will have some namespace :
using DB1DBModel;
using DB2DBModel;
Class MyClass
{
void SomeMethod()
{
// table with same name MyTable in first edmx
DB1DBModel.EntitiesXYZ.MyTable=new DB1DBModel.EntitiesXYZ.MyTable();
// tables with same name MyTable in second edmx
DB2DBMode2.EntitiesABC.MyTable=new DB2DBMode2.EntitiesABC.MyTable();
}
}
// Hope this works

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

Adding a MVC 4 controller using entity framework 5 database first

I'm trying to configure an MVC 4 application using EF 5 against the System.Web.Providers Membership DB. The ADO.NET Entity Data Model appears correct. The classes generated by the EF 5.x code generator look ok, but do not have a [Key] attribute. When I try to create a User Controller, I get the following error:
Microsoft Visual Studio
Unable to retrieve metadata for 'Citrius.Admin.User'. One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Membership' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Profile' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Memberships' is based on type 'Membership' that has no keys defined.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Profiles' is based on type 'Profile' that has no keys defined.
I thought I saw a walkthrough of this, using these versions, but cannot find it. I've tried to find a solution but all the examples are of previous versions.
Am I too far out on the bleeding edge?? Any help would be appreciated...
Why dont you assign the Key manually?
Go into each one and add [Key] above the field that should be the Key.
That should get rid of these errors.

Resources