带有自引用实体的实体框架代码优先存储库模式

本文关键字:实体 存储 模式 框架 自引用 代码 | 更新日期: 2023-09-27 17:50:32

我正在尝试在。net 4.5上实现EF5的存储库/工作单元模式,如下所述: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。这一切都很好,直到我尝试使用如下所述的自引用实体:http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code。当我尝试做任何事情(获得指定实体,获得所有实体,添加实体等)与包含自引用实体(FieldType)的存储库时,我在UnitOfWork类的fieldtyperrepository的getter上得到stackoverflowexception。别担心,在stackoverflow上发布stackoverflowexception的讽刺意味并没有在我身上消失。我读过不少关于EF存储库模式的SO文章,但还没有看到任何将它们与自引用实体相结合的文章。

我尝试过的事情:

  • 在FieldType实体上使用FluentAPI而不是属性-没有更改
  • 直接使用上下文对象——这工作得很完美,实体被添加到DB中并正确地相互引用,不幸的是,这违背了存储库模式的目的
  • 使用非自引用实体的存储库-工作很好
  • 使用。net 4.0和。net 4.5的EF5 -相同的结果
我代码:

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(或任何类)

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();
    }

带有自引用实体的实体框架代码优先存储库模式

感谢Gert,帮助我认识到这不是EF或自引用类型的问题,而是我从自身调用fieldtyperrepository的get方法…http://www.youtube.com/watch?v=g6GuEswXOXo