如何实现IEnumerable以正确枚举ObjectSet?

时间:2014-01-03 17:27:24

标签: c# entity-framework ienumerable objectcontext objectset

我的主要目标是覆盖ObjectSet的DeleteObject方法。我正在使用EntityFramework 6和我从EF 4.x迁移的ObjectContext。编辑:我修改了创建ObjectContext的T4模板,将上下文中的所有ObjectSet关联到使用MyObjectSet而不是标准,但我想以相同的方式使用它:context.HijackedSet.Where(i=> i.blah == 'blah')

编辑:我只遇到嵌套的ObjectSet调用问题,例如

(from p in context.SomeTable
let poco = new MyExcellentPOCO
{
   Name = p.Name,
   OtherProperty = context.UnrelatedTable.Where(i=> i.LimitingFactor = x)
}
select poco).ToList()

不幸的是,ObjectSet使用了一个我无法从中继承的内部构造函数。相反,我使用ObjectSet属性创建了自己的版本,并传递给所有ObjectSet方法的属性

代码:

public class MyObjectSet<TEntity> : IObjectSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable where TEntity : class
{
    public MyObjectSet(ObjectSet<TEntity> objectSet)
    {
        ObjectSet = objectSet;
    }

    public ObjectSet<TEntity> ObjectSet { get; set; }

    public void DeleteObject(TEntity entity)
    {
        if (entity is IEnforceLogicalDelete)
        {
            ((IEnforceLogicalDelete)entity).IsDeleted = true;
        }
        else
        {
            ObjectSet.DeleteObject(entity);
        }
    }

    public void AddObject(TEntity entity)
    {
        ObjectSet.AddObject(entity);
    }

    public void Attach(TEntity entity)
    {
        ObjectSet.Attach(entity);
    }

    public void Detach(TEntity entity)
    {
        ObjectSet.Detach(entity);
    }

    public IEnumerator<TEntity> GetEnumerator()
    {
        return ((IEnumerable<TEntity>)ObjectSet).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<TEntity>)ObjectSet).GetEnumerator();
    }

    public Type ElementType
    {
        get { return typeof(TEntity); }
    }

    public Linq.Expressions.Expression Expression
    {
        get
        {
            return ObjectSet.AsQueryable<TEntity>().Expression;
        }
    }

    public IQueryProvider Provider
    {
        get { return ObjectSet.AsQueryable<TEntity>().Provider; }
    }

    public ObjectQuery<TEntity> Include(string path)
    {
        return ObjectSet.Include(path);
    }        
}

MyObjectSet,因为它是在上下文中实现的:

public MyObjectSet<Address> Addresses
{
    get
    {
        if ((_Addresses == null))
        {
            _Addresses = new MyObjectSet<Address>(base.CreateObjectSet<Address>("Addresses"));
        }
        return _Addresses;
    }
}
private MyObjectSet<Address> _Addresses;

我检查了ObjectQuery类(ObjectSet继承自ObjectQuery),并将IEnumerator IEnumerable.GetEnumerator()实现为return ((IEnumerable<T>)this).GetEnumerator();。我对该属性的使用是否会改变结果? return ((IEnumerable<TEntity>)ObjectSet).GetEnumerator();

0 个答案:

没有答案