Question

I'm new to C# programming and I'm starting to learn the MVC4 framework. I decided to just dive in with a small web app idea for a mentoring program. I've come to a problem with adding a mentee to the system. I wasn't able to provide a diagram of the table relationship that I need help with so here goes...

I have 3 tables:

Address: address_id address1 address2 city ......

Mentee: mentee_id first_name middle_name last_name ......

Mentee_Address: mentee_id address_id

Of course EF doesn't recognize the cross reference table so the Models class for Mentee and Address:

Mentee Class:

public partial Class mentee
{
  public mentee()
  {
     this.addresses = new HashSet<address>();
  }

  public int mentee_id { get; set; }
  public string first_name { get; set; }
  public string middle_name { get; set; }
  public string last_name { get; set; }

  public virtual ICollection<address> addresses { get; set; }
}

Address Class:

public partial Class address
{
  public address()
  {
     this.mentees = new HashSet<mentee>();
  }

  public int address_id { get; set; }
  public string address1 { get; set; }
  public string address2 { get; set; }
  public string city { get; set; }

  public virtual ICollection<mentee> mentees { get; set; }
}

In my create view, i'm trying to add the student and address record along with keeping the relationship intact with addresses and mentees. I've read that EF does this without actually updating the cross reference table Mentee_Address. If so can someone provide a detailed explanation, if not, i need a way of accessing the cross reference table so that it can be updated.

public ActionResult Create(ViewModels.MenteeViewModel menteeViewModel)
{
  if (ModelState.IsValid)
  {
    db.mentees.Add(menteeViewModel.mentee);
    db.addresses.Add(menteeViewModel.address);
    db.SaveChanges();
  }
}
Was it helpful?

Solution

You create the relationship between mentee and address by adding the address to the mentee.addresses collection (or the other way around, it doesn't matter), like this:

if (ModelState.IsValid)
{
    menteeViewModel.mentee.addresses.Add(menteeViewModel.address);
    db.mentees.Add(menteeViewModel.mentee);

    db.SaveChanges();
}

You don't need to add the address to the context explicitly in this example because it will happen automatically together with adding the mentee. The code will INSERT a new mentee to the database, a new address and a link record into the link table Mentee_Address. I'm not sure if you want to insert both mentee and address, but that is what your original code would do as well. My example above just adds the link record to the procedure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top