Entity Framework: Many to Many relationships

A many-to-many relationship in CodeFirst is similar to a one-to-many relationship. The highlighted fields are the only lines you have to add, everything else is the same.

manytomany

namespace g20161005_ChurchData
{
  public class Person
  {
    public Person()
    {
      this.Parishes = new HashSet<Parish>();
    }
    public int id { get; set; }
    public string fname { get; set; }
    public string lname { get; set; }
    public virtual ICollection<Parish> Parishes { get; set; }
  }

  public class Parish
  {
    public Parish()
    {
      this.Persons = new HashSet<Person>();
    }
    public int id { get; set; }
    public int PersonID { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
  }
}

The above class file has two classes: one for person, one for parish. A person can belong to more than one parish, and a parish can have many persons.
Think of it as a person can have parishes and a parish can have persons.

This is done via a linking table without payload.

The contexts file should look like:

using System.Data.Entity;

namespace g20161005_ChurchData
{
  public class Contexts : DbContext
  {
    public DbSet<Person> Persons { get; set; }
    public DbSet<Parish> Parishes { get; set; }
  }
}

Finally, the calling code should look like this

namespace g20161005_ChurchData
{
  class Program
  {
    static void Main(string[] args)
    {
      temp1();
    }
    static void temp1()
    {
      var cp = new Person
      {
        fname = "Greg",
        lname = "Orcutt";
      };

      using (var Context = new Contexts())
      {
        Context.Persons.Add(cp);
        Context.SaveChanges();
      }
    }
  }
}

d

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s