title: Entity Framework Code First Repository Pattern with Self Referencing Entity
body: <p>I'm trying to implement the Repository/Unit-of-Work pattern for EF5 on .NET 4.5 as described here: <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="nofollow">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application</a>. This all works great until I try to use self-referencing entities as described here: <a href="http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code" rel="nofollow">http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code</a>. When I try to do anything (get a specify entity, get all entities, add an entity, etc.) with the repository that contains the self referencing entity (FieldType) I get a stackoverflowexception on the getter of the FieldTypeRepository in my UnitOfWork class. Don't worry, the irony of posting a stackoverflowexception on stackoverflow isn't lost on me. I've read quite a few SO articles about the repository pattern for EF but haven't seen anything combining them with self-referencing entities.</p>
  
  <p>Things I've tried:</p>
  
  <ul>
  <li>Using FluentAPI instead of attributes on the FieldType entity - no change</li>
  <li>Using the Context object directly - this works perfectly, entities are added to the DB and reference each other properly, unfortunately that defeats the purpose of the repository pattern</li>
  <li>Using the repository for non-self referencing entities - works great</li>
  <li>Using EF5 for .NET 4.0 and .NET 4.5 - same results</li>
  </ul>
  
  <p>My code:</p>
  
  <p>FieldType.cs</p>
  
  <pre><code>public class FieldType
  {
      [Key]
      [DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
      public int FieldTypeId { get; private set; }
  
      public string Name { get; set; }
  
      public string Description { get; set; }
  
      public int? ParentFieldTypeId { get; set; }
  
      [ForeignKey("ParentFieldTypeId")]
      public virtual FieldType ParentFieldType { get; set; }
  }
  </code></pre>
  
  <p>UnitOfWork.cs</p>
  
  <pre><code>public class UnitOfWork : IDisposable
  {
      private Context context = new Context();
  
      private Repository&lt;FieldType&gt; fieldTypeRepository;
  
      public Repository&lt;FieldType&gt; FieldTypeRepository
      {
          // EXCEPTION OCCURS HERE
          get
          {
              if (this.fieldTypeRepository == null)
              {
                  this.fieldTypeRepository = new Repository&lt;FieldType&gt;(this.context);
              }
  
              return this.FieldTypeRepository;
          }
      }
  
      public void Save()
      {
          this.context.SaveChanges();
      }
  }
  </code></pre>
  
  <p>Context.cs</p>
  
  <pre><code>public class Context : DbContext
  {
      public Context()
          : base("echo")
      {
      }
  
      public DbSet&lt;FieldType&gt; FieldTypes { get; set; }
  }
  </code></pre>
  
  <p>Repository.cs</p>
  
  <pre><code>public class Repository&lt;TEntity&gt; where TEntity : class
  {
      private Context context;
  
      private DbSet&lt;TEntity&gt; dbSet;
  
      public Repository(Context context)
      {
          this.context = context;
          this.dbSet = context.Set&lt;TEntity&gt;();
      }
  
      public virtual IEnumerable&lt;TEntity&gt; Get(
          Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
          Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
          string includedProperties = "")
      {
          IQueryable&lt;TEntity&gt; query = this.dbSet;
  
          if (filter != null)
          {
              query = query.Where(filter);
          }
  
          foreach (var includeProperty in includedProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
          {
              query = query.Include(includeProperty);
          }
  
          if (orderBy != null)
          {
              return orderBy(query).ToList();
          }
          else
          {
              return query.ToList();
          }
      }
  
      public virtual TEntity GetById(object id)
      {
          return this.dbSet.Find(id);
      }
  
      public virtual void Insert(TEntity entity)
      {
          this.dbSet.Add(entity);
      }
  
      public virtual void Delete(object id)
      {
          TEntity entityToDelete = this.dbSet.Find(id);
          this.Delete(entityToDelete);
      }
  
      public virtual void Delete(TEntity entityToDelete)
      {
          if (this.context.Entry(entityToDelete).State == EntityState.Detached)
          {
              this.dbSet.Attach(entityToDelete);
          }
  
          this.dbSet.Remove(entityToDelete);
      }
  
      public virtual void Update(TEntity entityToUpdate)
      {
          this.dbSet.Attach(entityToUpdate);
          this.context.Entry(entityToUpdate).State = EntityState.Modified;
      }
  }
  </code></pre>
  
  <p>SecurityController.cs (or any class really)</p>
  
  <pre><code>public class SecurityController : Controller
  {
      public ActionResult Login()
      {
          using (UnitOfWork unitOfWork = new UnitOfWork())
          {
              var fieldType = unitOfWork.FieldTypeRepository.GetById(1);
              //THIS COULD BE ANY TYPE OPERATION
          }
  
          return this.View();
      }
  </code></pre>