title: Serialization of Entity Framework objects with One to Many Relationship
body: <p>I am attempting to use EF with Code First and the Web API.  I don't have any problems until I get into serializing Many-to-Many relationships.  When I attempt to execute the following web api method below I get the following error message:</p>
  
  <pre><code>public class TagsController : ApiController
  {
  
          private BlogDataContext db = new BlogDataContext();
  
          // GET api/Tags
          public IEnumerable&lt;Tag&gt; GetTags()
          {
              return db.Tags.AsEnumerable();
          }
  }
  </code></pre>
  
  <p>I get the following error:</p>
  
  <blockquote>
    <p>'System.Data.Entity.DynamicProxies.Tag_FF17EDDE6893000F7672649A39962DB0CA591C699DDB73E8C2A56203ED7C7B6D'
    with data contract name
    'Tag_FF17EDDE6893000F7672649A39962DB0CA591C699DDB73E8C2A56203ED7C7B6D:<a href="http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies" rel="noreferrer">http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies</a>'
    is not expected. Consider using a DataContractResolver or add any
    types not known statically to the list of known types - for example,
    by using the KnownTypeAttribute attribute or by adding them to the
    list of known types passed to DataContractSerializer.</p>
  </blockquote>
  
  <p>I have read some SO articles (<a href="https://stackoverflow.com/questions/11315311/using-navigation-properties-in-entity-framework-code-first">article 1</a>, <a href="https://stackoverflow.com/questions/9071118/efcf-many-to-many-in-a-detached-context">article 2</a>) that the fix is to add the following attribute:</p>
  
  <blockquote>
    <p>[DataContract (IsReference=true)]</p>
  </blockquote>
  
  <p>but this has had no effect.  Also using [IgnoreDataMember] does not have an effect.  The only option that does seem to work is to set Configuration.ProxyCreationEnabled to false.  Is this my only option?  Am I missing something?</p>
  
  <p><strong><em>Sample POCO objects:</em></strong></p>
  
  <p><strong>Tag</strong></p>
  
  <pre><code>[DataContract(IsReference = true)]
  public class Tag
  {
          public Tag()
          {
              this.Blogs = new HashSet&lt;Blog&gt;();
          }
  
          [Key]
          [DataMember]
          public int Id { get; set; }
  
          [DataMember]
          public string Name { get; set; }
  
          [IgnoreDataMember]
          public virtual ICollection&lt;Blog&gt; Blogs { get; set; }
  }
  </code></pre>
  
  <p><strong>Blog</strong></p>
  
  <pre><code>[DataContract(IsReference = true)]
  public class Blog
  {
      public Blog()
      {
          this.Tags = new HashSet&lt;Tag&gt;();
      }
  
      [Key]
      [DataMember]
      public int Id { get; set; }
  
      [DataMember]
      public string Name { get; set; }
  
      [IgnoreDataMember]
      public virtual ICollection&lt;Tag&gt; Tags { get; set; }
  }
  </code></pre>