EF: How to eliminate a joi-table in the model while still respecting relationship among tables in the underline database? - entity-framework

Let's say I have a Database with 3 tables: Keywords, Documents, and KeywordDocuments. KeywordDocuments has only 3 columns, KeywordDocumentID, KeywordID, and DocumentID.
The relationship between Documents and KeywordDocuments is the same as Keywords and KeywordDocuments, i.e. one-to-many.
Watching Julie Lerman's video on EF, she said that we don't need KeywordDocuments's entity in the model. How do I eliminate that entity while making sure that in the relationship will be respected in the underline database?
Thanks for helping

Remove the KeywordDocumentID column from the KeywordDocument table. It will then contain only the foreign key columns from the tables for which it represents a many to many relationship.
Create a new composite primary key on the KeywordDocument table which includes both the KeywordID and the DocumentID columns. This will replace the original primary key that you had on the KeywordDocumentID column - that key would have been deleted along with the column.
A table such as this will not result in an entity being generated in the model. Rather, both of the other entities (Keyword and Document in this case) will have navigation properties based on EntityCollection. Document will have a collection of Keywords and vice verca.

Related

Shared Postgres Relation Best Practices

What is the best practice to encode this relationship in a postgres database schema?
Given the following entities: Document, Profile, Message
And the following relationships:
One Profile to many Documents
One Message to many Documents
Essentially documents are a shared resource used by other entities. Should I use different Join Tables for each related entity? Is there some other way to set this up? It is possible in the future that other entities will reference Documents
For anyone who finds this post and wants an actual answer: The foreign key for the relation HAS to be on the many-to-one side of the relationship or there has to be a join table mapping the relation. You cannot store multiple foreign keys in a single column on the one-to-many side of the relationship.
A one-to-many relationship is modeled with a foreign key, in this case in the documents table. If you need two such relationships, define two foreign keys.

Adding DateTime field to many-to-many EF Code First relationship

I am using EF 6 Code-First, table per type, and I have two concrete classes Group and User. Group has a navigation property Members which contains a collection of User. I have mapped this many-to-many relationship in EF using Fluent syntax:
modelBuilder.Entity<Group>
.HasMany<User>(g => g.Members)
.WithMany(u => u.Groups);
I would like to be able to say when a member has joined a group so that I can query for, say, the newest member(s). I am not sure of how this is best accomplished within the framework.
I see the following options:
Create and use an audit table (ie GroupMembershipAudit consisting of Group, User, join/unjoin, and DateTime
Add a column to the autogenerated many-to-many table between User and Group
Is there anything within EF to facilitate this sort of storage of many-to-many historical info like this / append columns to the many-to-many relationship?
Add a column to the autogenerated many-to-many table between User and
Group
That is not possible - auto-generated junction tables can contain only keys (that is called Pure Join Table). According to Working with Many-to-Many Data Relationships article: If the join table contains fields that are not keys, the table is not a PJT and therefore Entity Framework cannot create a direct-navigation (many-to-many) association between the tables. (Join tables with non-key fields are also known as join tables with payload.)
Create and use an audit table (ie GroupMembershipAudit consisting of
Group, User, join/unjoin, and DateTime
Actually you should create GroupMembershipAudit entity. With Code First table will be generated, you don't need to create it manually.

How can I replicate core data model using a traditional relational database?

I have my app using core data with the data model below. However, I'm switching to a standard database with columns and rows. Can anyone help me with setting up this new database schema?
First of all you need to create tables for each of the Entities and their attributes (note I added "id" to each of the tables for relationships):
Routine (name, timestamp, id)
Exercise - this looks like a duplicate to me, so leaving one only here (muscleGroup, musclePicture, name, timeStamp, id)
Session (timeStamp, id)
Set (reps, timeStamp, unit, weight, id)
Now that you have tables that describe each of the entities, you need to create tables that will describe the relationships between these entities - as before table names are in capitals and their fields are in parenthesis:
RoutineExercises (routine_id, exercise_id)
SessionExercises (session_id, exercise_id)
ExerciseSets (exercise_id, set_id)
That's it! Now if you need to add an exercise to a routine, you simply:
Add an entry into Exercise table
Establish the relationship by adding a tuple into RoutineExercises table where routine_id is your routine ID and exercise_id is the ID of the newly created entry in the Exercise table
This will hold true for all the rest of the relationships.
NOTE: Your core data model has one-to-many and many-to-many relationships. If you want to specifically enforce that a relationship is one-to-many (e.g. Exercise can only have 1 routine), then you will need to make "exercise_id" as the index for the RoutineExercises table. If you want a many-to-many relationships to be allowed (i.e. each exercise is allowed to have multiple routines), then set the tuple of (routine_id, exercise_id) as the index.

Is this possible to model a "foreign key" into multiple tables with Entity Framework?

I have a MS SQL 2008 database, and I can't change its schema. I have to work with what it is.
It has three tables that relevant to the question.
Product table. The columns are:
Id (identity, PK)
Group (NOT NULL)
SubGroup (NOT NULL)
Code (Unique, NOT NULL)
Description
Contract table. The columns are:
Id (identity, PK)
Code (NOT NULL)
Descritpion
Discount table. The columns are:
Id (identity, PK)
Type (restricted to one of the four values:
'product',
'group',
'subgroup' or
'contract') (NOT NULL)
Object (depending on the value of Type refers one of the four:
Product.Code
Product.Group
Product.SubGroup
Contract.Code) (NOT NULL)
Value (NOT NULL)
The idea is that the discount can be applied to either of the four. I'd like to reiterated, that this is the database design that I can't change.
With Entity Framework I can query the tables all right with joins but I can't use navigation properties out of the box, because navigation properties are generated based on foreign key relationships from database, and you can't define "conditional" relationship in MS SQL, where the field object relates to one table when field type contains this value and relates to another table when the value is different.
My question is this: Is this possible to define classes and mappings with Entity Framework, so that I can use navigation properties in this scenario? For example, I do Discount.Object and I receive either Contract object or Product object in response, and if this is a Product object it's retrieved on the right property.
Is this, or something similar possible, or joins is the best I can do?
You said that "this is the database design that I can't change", but without changing existing tables, can you at least add views?
If you can, you can create a view for the Discount table that has four different nullable columns for each relationship. That would map nicely in EF as four navigation properties.
After you do that, if you still want a combined column, you could add your own property to the Discount entity that will return an object by checking which of the four navigation properties is not null, and returning the linked entity.
You cannot create a relational database like this. You need separate columns for the keys to each potential parent row.

Trouble inheriting from another entity

I'm having trouble configuring entity relationships when one entity inherits from another. I'm new to ADO Entity Framework -- perhaps someone more experienced has some tips for how this is best done. I'm using .net 4.
Database tables with fields:
Products (int ID, nvarchar Description)
FoodProducts (int ProductID, bit IsHuge)
Flavors (int ID, int FoodProductID, nvarchar Description)
There are constraints between Products and FoodProducts as well as FoodProducts and Flavors.
Using the designer I create a model from the database. The designer seems to get it right, with a 1:0..1 association between Product and FoodProduct entities, and 1:* association between Flavor and FoodProduct. No errors when I save or build.
Next I set FoodProduct entity to inherit from Product entity. Then I get errors concerning relationship between Product and FoodProduct. Ok, starting fresh, I first delete the relationship between Product and FoodProduct before setting the inheritance. But now I get errors about the relationship between FoodProduct and Flavor. So I delete and then recreate that relationship, connecting Flavor.ID to FoodProduct.ProductID. Now I get other errors.
My question is this: Should I instead be creating relationship between Flavor.FoodProductID and Product.ID? If so, I assume I then could (or should) delete the FoodProduct.ProductID property. Since my database will have many of these types of relationships, am I better off first creating the entity model and exporting the tables to SQL, or importing the database schema and then making many tweaks?
My intent is that there will be several types of products, some of which require many additional fields, some of which do not. So there may be zero or one FoodProducts records associated with each Product record. At least by my thinking, the table for each sub-type (FoodProducts) should be able to "borrow" the primary key from Products (as a FK) to uniquely identify each of its records.
You can find a screen capture here: http://img218.imageshack.us/img218/9720/entityframework.jpg (I'd embed the img but haven't earned the requisite rep' yet!)
Well, I deleted the FoodProduct.ProductID field, as it should always return the same value as Product.ID anyway. Then, as you hinted, I had to manually map the Products.ID field to FoodProducts.ProductID field. Errors resolved. I'll write a little code to test functionality. Thanks for the "observations"!
Couple of observations:
FoodProducts needs a primary key (e,g identity - FoodProductID). Are you sure it should be a 1:0..1 between Food and FoodProducts? I would have thought it should be 1:0..*. For this cardinality to work you need a unique PK on this table.
When you setup inheritance for entities, the parent entity's properties are inherited. So FoodProducts will inherit ID from the Product table.
BUT, on the physical model (database), this field still needs to be mapped to a column on the FoodProducts table - which is why you need the identity field.
After you setup inheritance, you still need to map all the columns on the derived tables. My money is on you have not mapped "ID" on FoodProducts to any column.
If you screencapped your model and show the errors you are getting it would be much easier to diagnose the issue.