Thanks Gert, for helping me realize that it's not a problem with EF or self-referencing types but rather that I was calling the get method for the FieldTypeRepository from itself... http://www.youtube.com/watch?v=g6GuEswXOXo
Entity Framework Code First Repository Pattern with Self Referencing Entity
Question
I'm trying to implement the Repository/Unit-of-Work pattern for EF5 on .NET 4.5 as described here: 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. This all works great until I try to use self-referencing entities as described here: http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code. 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.
Things I've tried:
- Using FluentAPI instead of attributes on the FieldType entity - no change
- 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
- Using the repository for non-self referencing entities - works great
- Using EF5 for .NET 4.0 and .NET 4.5 - same results
My code:
FieldType.cs
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; }
}
UnitOfWork.cs
public class UnitOfWork : IDisposable
{
private Context context = new Context();
private Repository<FieldType> fieldTypeRepository;
public Repository<FieldType> FieldTypeRepository
{
// EXCEPTION OCCURS HERE
get
{
if (this.fieldTypeRepository == null)
{
this.fieldTypeRepository = new Repository<FieldType>(this.context);
}
return this.FieldTypeRepository;
}
}
public void Save()
{
this.context.SaveChanges();
}
}
Context.cs
public class Context : DbContext
{
public Context()
: base("echo")
{
}
public DbSet<FieldType> FieldTypes { get; set; }
}
Repository.cs
public class Repository<TEntity> where TEntity : class
{
private Context context;
private DbSet<TEntity> dbSet;
public Repository(Context context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includedProperties = "")
{
IQueryable<TEntity> 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;
}
}
SecurityController.cs (or any class really)
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();
}
Solution