Entity Framework: One or Zero to Many relationships

To create a relationship that looks like this:

1or0tomany

The classes file should look like:

namespace g20161005_ChurchData
{
  public class Person
  {
    public Person() { }
    public int id { get; set; }
    public string fname { get; set; }
    public string lname { 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, but can belong to zero.
What establishes the relationship are the highlighted fields. It is essentially saying a parish has persons.

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();
      }
    }
  }
}

 

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