title: Mvc3 Database first relationships
body: <p>I am working on a project with ASP.Net MVC3 EF4.1 and relationships between tables through foreign keys. I am using the database first approach and have three tables: Calendar, Calendar Users and Users. The relationship is that a Calendar can have many users and users can have many calendars.</p>
  
  <p>When someone is creating the calendar he/she is also supposed to select the number of users that will have access to the calendar. But now when I am about to save the changes to the database in the controller thats when I get confused. In the generated classes there are also virtual ICollections that I suppose represent the foreign keys somehow. But I can't figure out how I am supposed to handle them? So how is it supposed to work? Should I be able to add the changes to the virtual ICollections and then just do db.SaveChanges() and it will work by itself or am I supposed too handle that manually? </p>
  
  <p>If I am supposed to handle it manually should I then add the users, add the calendar and then add the keys in the CalendarUsers table to bind them together? I've seen some examples from code first where they have clarified the relationship by entering code in the OnModelCreating method but when using Database first it just contains:  <code>throw new UnintentionalCodeFirstException();</code>? Hoping you perhaps can clarify it for me a bit.</p>
  
  <p>Added the classes generated by the DBcontext Generator below:</p>
  
  <pre><code>public partial class Calendar
  {
      public Calendar()
      {
          this.CalendarUsers = new HashSet&lt;CalendarUser&gt;();
      }
  
      public int CalendarId { get; set; }
      public string CalendarTitle { get; set; }
      public string CalendarDescription { get; set; }
      public long UserId { get; set; }
  
      public virtual User User { get; set; }
      public virtual ICollection&lt;CalendarUser&gt; CalendarUsers { get; set; }
  }
  
  public partial class CalendarUser
  {
      public int CalendarUserId { get; set; }
      public int CalendarId { get; set; }
      public long UserId { get; set; }
      public Nullable&lt;bool&gt; IsAdmin { get; set; }
  
      public virtual Calendar Calendar { get; set; }
      public virtual User User { get; set; }
  }
  
  public partial class User
  {
      public User()
      {
          this.Calendars = new HashSet&lt;Calendar&gt;();
          this.CalendarUsers = new HashSet&lt;CalendarUser&gt;();
      }
  
      public long UserId { get; set; }
      public string Name { get; set; }
  
      public virtual ICollection&lt;Calendar&gt; Calendars { get; set; }
      public virtual ICollection&lt;CalendarUser&gt; CalendarUsers { get; set; }
  }
  </code></pre>