Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Hi all!im working on code first database , i created my own model in Model folder and im not working with entities . I have a model class that is named Event and consists of the fields :EVENTID(STRING) DATE DESCRIPTION IMAGE . What am i trying to do now is , to create another class named Home with columns like HOMEID(STRING) DESCRIPTION LINK , and this table class Home must have a many to many relationship with the class Event .i read this tutorial from this link https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/how-to-create-relationships-between-entities-in-the-entity-framework-code-first-approach , but something isnt clear . Insted of its own columns , i want to add EventID as navigation field ,as foreign key in Home class , so that it will navigate to field ID of Event class. Lets pretend i have a row inserted already in database in two of the tables :
Event:
EVENTID:TEST

DATE:01-01-2001

DESCRIPTION:TEST

IMAGE:TEST

_______Home:_________________
HOMEID:TEST1

DESCRIPTION:TEST1

LINK:TEST1

So now , when i use create view to add a Home object , be able to do something like this :
Create Home View fields:

HOMEID : test2

DESCRIPTION:test2

LINK : test2

EVENTID :(HERE WE TYPE THE ID OF EVENT OBJECT THAT EXIST IN DATABASE ALREADY)  TEST

Then when i render the Details view of this created Home object with id 'test2' , be able to see something its own fields and Event table related fields :
DETAILS VIEW :
HOMEID : test2

DESCRIPTION:test2

LINK : test2

EVENTID:TEST

DATE:01-01-2001

DESCRIPTION:TEST

IMAGE:TEST


i APPRICIATE EVERY HELP.THANKS A LOT IN ADVANCE.

What I have tried:

--------------------------------------------------
Posted
Updated 15-Jan-18 13:17pm
v3

1 solution

The standard method of creating a many-to-many join is to create what is known as a junction table.
Based on what you have provided above (Table: Event & Table: Home) you would create a third table - normally named Event__Home that consists of the following columns;
a) Primary Key
b) Foreign Key to Event table
c) Foreign Key to the Home table

When you add a new reference between Event & Home a new record is created in the Event__Home table that comprises of the Event Id & the Home Id.
The Models for Event & Home should be then updated to include collections from the Event__Home table.
MVC will allow you to traverse these to display additional values from the relevant table.

The below article will give you additional information on Many-to-Many joins etc;
MSDN: How-To: Many to Many Relationships[^]

Kind Regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900