Error in One-to-many Relationship in Entity Framework - entity-framework-4.1

I have the following tables
Users
----------
UserId (int)
Name (varchar)
Stores
----------
StoreId (int)
Name (varchar)
Owner (int) (FK to UserId in Users table)
and the following entities in the edmx file
User{
properties
UserId
Name
}
Store{
properties
StoreId
Name
Owner
navigation proeprties
User
}
I am using a POCO approach. Mapping the edmx file to my POCO entities. Fetching Users works fine, but when I try to create a new user it gets saved in the database successfully but throws the following exception
"The changes to the database were committed successfully, but an error
occurred while updating the object context. The ObjectContext might be
in an inconsistent state. Inner exception message: Metadata
information for the relationship 'FK_Stores_Users_Owner' could not be
retrieved. If mapping attributes are used, make sure that the
EdmRelationshipAttribute for the relationship has been defined in the
assembly. When using convention-based mapping, metadata information
for relationships between detached entities cannot be determined.
Parameter name: relationshipName"

I see you are using EF 4.1 together with EDMX, then you have to declare the Key constrains by yourself either use attributes or Fluent-API. Since EF 4.1 is not compatible with traditional constraint configuration defined in XML.
Furthermore, make sure you use "ADO.NET DbContext generator" rather than "ADO.NET POCO Entity Generator".

Related

Unable to retrieve metadata for model. One or more Validation errors were detected during model generation: table has no key defined

Following on from this question here:Entity Framework Reverse Engineer using Power Tools - No Primary Keys
I've reverse engineered a database using Entity Framework Power Tools Beta 2.
This has created a large number of POCO's and a mappings folder with the entity mappings.
When I attempt to create a controller using the Add Controller Dialog I get the following message box come up:
Unable to retrieve metadata for cruise model. One or more Validation errors were detected during model generation:
\tSystem.Data.Entity.EmdEntityTypes:: cruise table has no key defined. Define the key for this EntityType.
This repeats many times for all the related tables to the original one for which I was trying to create a controller.
The Controller itself is never created and on pressing OK I'm returned to the Add Controller Dialog.
The model in question definitley has a primary key defined in it's mapping file:
// Primary Key
this.HasKey(t => t.cruise_ID);
What am I doing wrong?
How does the controller find the mapping classes?
I've been able to replicate the error your receive, and it's related to trying to create a controller for the Model itself, rather than for the entity type.
The MVC scaffolding is designed to target an entity, then the related context - are you sure you're selecting the right items in the drop down?
In This image:
Your model drop down (Mine shows A (MVCExamples.Models)) should refer to what I assume is your cruise entity.
Your Data Context should be the DbContext that gets created (Mine shows Entities (MVCExamples.Models))
ADD :
using System.ComponentModel.DataAnnotations;
and a primary key to db class is calling'

Entity type not created for table with composite key

I'm using VS 2010, Entity Framework 4.3 and MySql.Data.Entity v6.3.5 to work with a MySQL DB with a couple dozen tables. I use the ADO.NET DbContext Generator.
Everything works well enough other than two tables don't get Entities created for them. Both have a similar structure in that they have a composite key composed of foreign keys to other tables. So, one is a region_flavor table that maps the (ice cream) flavors assigned to a particular sales region. It looks like so
region_flavor
-------------
RegionId INT(10) PK NN
Flavor VARCHAR(64) PK NN
RegionId is a FK to the regions table and Flavor is a FK to the ice_cream table.
There's another table with essentially the same situation.
When I do an "Update from Database", I see that there is, in the Model Browser, the table region_flavor listed under my IceCreamModel.Store\Tables / Views folder. But under my IceCreamModel\Entity Types folder there's no Entity Type.
I don't receive any .edmx errors when I do the update from the DB.
Perhaps I'm missing something here. Ideas?
I can post more info if that's helpful.
It is normal behavior. This is junction table used to model many-to-many relation in database. If it doesn't contain any additional column EF doesn't need to map it to entity because many-to-many relation is modeled directly and translated to table rows internally by EF.

Entity Framework 4.2 - How to realize TPT-Inheritance with Database-generated Primarykey Value?

I want to use the EF (4.2) in the following scenario:
There exists a database already (so I chose the database-first approach) and it is a SQL Anywhere DB.
I want to use persistence-ignorant business objects, so I use the DbContext Template to generate POCO classes from the EDM.
There is one simple inheritance hierarchy among my entities: an abstract base entity and two concrete derived entities.
In the database there is one table for each type of the inheritance hierarchy (Table-Per-Type Strategy).
Each of these three tables has a primary key column (Id, type:integer), and the association of a concrete entity to the base entity is done by having the same Id in both tables (that means that the primary key (Id) of the concrete type tables is at the same time a foreign key to the base table; a pretty common approach I think).
I had to define the Inheritance manually in the designer, since the EDM assistant does not automatically recognize, that is want to have an inheritance association between the described entities.
Until this point there wasn't any bigger problem. Now to the issue at hand:
There is a restriction for the database I use: Primarykey values have to be generated by the database, using a database function.
I want to call this function in a before-insert-trigger defined on the base-table.
To let the entity framework know that a value is generated by the database, I set the StoreGeneratedPattern property of the Id Property of the base-entity to Identity (As I understood, this is the way to tell EF to get the generated value after inserting a new instance of an entity).
When I create a new instance of a derived entity, add it to the corresponding DbSet of the DbContext and call SaveChanges on the context, a DbUpdateException is thrown, stating that a foreignkey constraint is violated.
By checking the request-log of the DB, I see that the base entity got inserted in the base table, but on inserting the row in the derived table, the above mentioned error occurs, because it obviously doesn't use the newly generated Id of the new entry in the base table.
Since I don't think there is much I can do on a database level against that, the question is, if the EDM or DbContext can be configured (or modified) to insert the base row first, then take the generated Id and use it for insertion of the derived row.
I know there are several way to avoid this situation (not using inheritance, using a stored procedure to insert a new derived entity, calling the id-generating db-function before inserting and set the Id property myself on the entity), but at the moment the above-described behavior would be the most preferable, so I want to make sure not to overlook something before deciding for any "plan B".
Any suggestions on this topic are much appreciated,
Thanks in advance.
Here is the code of the trigger:
ALTER TRIGGER "TRG_GENERATE_ID" before insert order 1 on
BASE_TABLE
referencing new as NewEntry
for each row
begin
declare NewID integer;
set NewID = F_GET_NEW_ID('BASE_TABLE', NewEntry.SOME_OTHER_ID);
set NewEntry.ID = NewID
end
The function "F_GET_NEW_ID" is called in the trigger to generate the new ID for a new entry in the base table. It has two parameters:
"Tablename" -> The name of the table for which a new ID should be generated,
and a second parameter that takes the value of a standardcolumn in all tables of the database (it is required to generate the new ID).

JPA Entities - MySQL tables Mapping

Database tables:
Tutor( {PK}tutorId, name )
Module( {PK}moduleId, name, {FK}tutorId )
Relationship Tutor -> Module (OneToMany)
Questions:
If you create the domain model
classes with JPA annotations, the
corresponding database tables are
auto-created with the same columns as the annotated fields of the class?
Do you create the database first
and then the JPA classes with the
same fields as the database table
columns?
How do you model foreign key constraints with JPA
(1) and (2) are depended on your situation. you can create domain model class first and it will generate table and columns which are the similar to the fields. In addition, you can establish a database first (it is easy to design and have better view of the whole database.), then map the tables to your domain class.
about (3) you can try this link

Navigating by foreign keys in ADO.NET Entity Framework/MySQL

I am using ASP.NET MVC2 on top of a MySQL database in VS2008. I am using the MySQL ADO.NET connector 6.2.3 to provide the connection for the ADO.NET Entity Data Model.
This is mostly working ok, however navigating via foreign keys is causing me a real headache!
Here is a simplified example..
Car (Table)
CarID PK
Colour
Doors
ManufacturerID FK
Manufacturer (Table)
ManufacturerID PK
Name
In the edmx file I can see the 1-many relationship shown as a navigation property in the both the Car and Manufacturer tables. I create a Models.CarRepository that allows me to returns a IQueryable.
At the View I want to be able to display the Manufacturer.Name for each car. This is not accessible via the object I get returned.
What is best way to implement this? Have I encountered a limitation of the Entity Framework/MySQL combination?
Eager loading of the related records needs to be enabled in the Model Repository. Something like:
var allCars = from c in automobileEntites.Car.Include("Manufacturer")
select c;
This then makes the related records available for subsequent query/display.