title: Code First adding to collections? How to use Code First with repositories?
body: <p>EDIT: This happen only on larger scale projects with repositories. Is there anybody using EF4 with CodeFirst approach and using repositories? Please advise me.</p>
  
  <p>Hi. Im currently working with EF4 CodeFirst Classes. In my test project I got two classes, Author and Book (author got books). What I'm trying to do is that I have a AddBook in my Author class, but that wont seem to work like I can't Add it to the collection.. here are my classes and two different exceptions.</p>
  
  <pre><code> public class Book
  {
      public virtual int BookId { get; set; }
      public virtual string Title { get; set; }
      public virtual Author Author { get; set; }
  }
  
  public class Author
  {
      public virtual int AuthorId { get; set; }
      public virtual string Name { get; set; }
      public virtual ICollection&lt;Book&gt; Books { get; set; }
  
      public Author()
      {
          Books = new Collection&lt;Book&gt;();
      }
  
      public void AddBook(Book book)
      {
          book.Author = this;
          Books.Add(book);
      }
  }
  </code></pre>
  
  <p>exception: The property 'Books' on type 'Author_4CF5D4EE954712D3502C5DCDDAA549C8E5BF02A0B2133E8826A1AC5A40A15D2A' cannot be set because the collection is already set to an EntityCollection.</p>
  
  <p>I change the Author class to this</p>
  
  <pre><code>public class Author
  {
      public virtual int AuthorId { get; set; }
      public virtual string Name { get; set; }
      public virtual ICollection&lt;Book&gt; Books { get; set; }
  
      public void AddBook(Book book)
      {
          book.Author = this;
          Books.Add(book);
      }
  }
  </code></pre>
  
  <blockquote>
    <p>Exception: Object reference not set to
    an instance of an object.</p>
    
    <p>cannot be set because the collection
    is already set to an EntityCollection.</p>
  </blockquote>
  
  <p>And thats only natural that I get that exception because the Collection is not set to a new, but then I get that first exception. so how is this done with code first in EF?</p>
  
  <p>maybe I should add that my It might collide with my DbSet?</p>
  
  <pre><code>public class EntityContext : DbContext, IUnitOfWork
  {
      public DbSet&lt;Author&gt; Authors { get; set; }
      public DbSet&lt;Book&gt; Books { get; set; }
  
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
          modelBuilder.IncludeMetadataInDatabase = false;
      }
  
      public void Save()
      {
          SaveChanges();
      }
  }
  </code></pre>