Cathal O 'Donnell February 2016

MVC - Linking two Models using a foreign key

How would I add a foreign key linking my Club class and my ClubEvent class together in a one-to-many relationship where Club is the parent class and ClubEvent is the child.

These are the models I am using

public class Club
    {
        // Class to manage a single Club
        [Key]
        public int ClubID { get; set; 
    }//end Club



public class ClubEvent
    {
        [Key]
        public int EventID { get; set; }

      }

I want to connect these two tables so I can add events for a club so I can display only the relevant events for each club

Answers


Kyle Bachmann February 2016

This is pretty basic MVC, and if you need help with this stuff in the future please complete this tutorial: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application it is great!

Since ClubEvent is a 'child' of Club (meaning one club can have one or many events) you want to have the reference to the parent in the child. So, you will add a reference to clubEvent linking each instance of that object to the appropriate club. Add this to your ClubEvent Object..

public int ClubID {get; set;}

[ForeignKey("ClubID")]
public virtual Club Club {get;set;}

By adding the navigation property (virtual Club Club) you will be able to make a call to the parent object from the ClubEvent child. (club)this.ClubEvent.

displaying this is easily achieved by querying the ClubEvents table with the parent Club ID. Like:

var events = db.ClubEvents.Where(e => e.ClubID == id)

Where 'id' is the ClubID passed to the method in your controller.

Hope this helps, if you have any issues check this link out because it has great examples for every relation type in MVC.

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

Post Status

Asked in February 2016
Viewed 3,920 times
Voted 5
Answered 1 times

Search




Leave an answer