Conditional Include not working with Entityt Framework 5

醉酒当歌 提交于 2020-01-05 08:06:27

问题


I'm trying to use the Conditional Include (explained here, but it's not retrieving the child information. Why? I think I've followed all the steps... I'm using WebApi controllers and Visual Studio 2012

I've alread checked and I have doorTypes assigned to each house. It's a many to many relationship.

I have this:

DoorType has this property

public virtual ICollection<House> Houses{ get; set; }

House has this property

public virtual ICollection<Door> DoorTypes{ get; set; }

And I'm querying this method

public IEnumerable<House> GetList(string latitude, string longitude, string idHousesTypeList)
{
    IEnumerable<int> intIds = null;

    if (!string.IsNullOrEmpty(idHousesTypeList))
    {
        var ids = idHousesTypeList.Split(',');
        intIds = ids.Select(int.Parse);
    }

    var location = DbGeography.FromText(string.Format("POINT ({0} {1})", latitude, longitude), 4326);
    var count = 0;
    var radius = 0.0;
    IEnumerable<House> houses = null;

    while (count < 5 && radius < 500)
    {
        radius += 2.5;
        var radiusLocal = radius;

        var dbquery =
            from house in Uow.Houses.GetAll()
            where house.Location.Distance(location) / 1000 <= radiusLocal
            orderby house.Location.Distance(location)
            select new
            {
                house,
                doorTypes= from doorType in house.DoorTypes
                                where intIds.Contains(doorType.Id)
                                select doorType
            };


        houses = dbquery
        .AsEnumerable()
        .Select(p => p.house);

        count = houses.Count();
    }

    if (houses != null && houses.Any())
    {
        return houses;
    }

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

I'm using generic EFRepository

public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }

    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = DbContext.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query;
    }

    public virtual T GetById(long id)
    {
        return DbSet.Find(id);
    }

    public virtual IQueryable<T> GetByPredicate(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> query = DbContext.Set<T>().Where(predicate);
        return query;
    }

    public virtual IQueryable<T> GetByPredicateIncluding(System.Linq.Expressions.Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = DbContext.Set<T>().Where(predicate);
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query;
    }

    public virtual void Upsert(T entity, Func<T, bool> insertExpression)
    {
        if (insertExpression.Invoke(entity))
        {
            Add(entity);
        }
        else
        {
            Update(entity);
        }
    }

    public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Detached)
        {
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
    }

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }

    public virtual void Delete(int id)
    {
        var entity = GetById(id);
        if (entity == null) return; // not found; assume already deleted.
        Delete(entity);
    }
}

The output shows all the houses correctly but the array of doorTypes is empty. What am I missing?


回答1:


It's a many to many relationship.

That's the problem. Relationship Fixup does not work for many-to-many relationships, only for one-to-one or one-to-many relationships.

You need to build up the navigation property manually after the query is executed. But you can do it relatively simple in this case:

houses = dbquery
    .AsEnumerable()
    .Select(p => {
        p.house.DoorTypes = p.doorTypes;
        return p.house;
    });

It is the same reason why explicit loading of navigation collections into the context does not work for many-to-many relationships, see this question: EF 4.1 loading filtered child collections not working for many-to-many and the answer to it, especially the reference to Zeeshan Hirani's explanation about relationship fixup for a deeper background about the subject.




回答2:


It's not clear how your Uow.Houses.GetAll() implemented, but try to include DoorTypes into result, when you are getting all houses from context:

return context.Houses.Include("DoorTypes");

And make sure you are passing idHousesTypeLis with existing ids.

UPDATE: Include is a member of DbQuery. It becomes unavailable when you cast Set to IQueriable<T>. So, try this:

public class HouseRepository : EFRepository<House>
{
    public override IQueryable<House> GetAll()
    {
        return DbContext.Set<House>().Include("DoorTypes");
    }
}


来源:https://stackoverflow.com/questions/14271475/conditional-include-not-working-with-entityt-framework-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!