2016-03-09 2 views
1

В EF6, как самый эффективный способ получить всех детей объекта DbSet, где у объекта DbSet могут быть дети и дети в ICollection?EF6 - Как самый эффективный способ получить всех детей в ICollection?

Вот мой класс:

public class Simple 
{ 
    [Key] 
    public int id { get; set; } 
    public int? simpleId { get; set; } 
    [ForeignKey("simpleId")] 
    public virtual Simple simple { get; set; } 
    public virtual ICollection<Simple> simpleObjects { get; set; } 
} 

Вот код, который у меня есть:

public IQueryable<Simple> GetAll(params Expression<Func<Simple, object>>[] includeExpressions) 
{ 
    IQueryable<Simple> set = db.Simple; 

    foreach (var includeExpression in includeExpressions) 
    { 
     set = set.Include(includeExpression); 
    } 
    return set; 
} 

Я вызываю функцию со следующим кодом:

IQueryable<Simple> getAll = GetAll(o=> o.simpleObjects); 

Это возвращая все объекты Simple в DbSet.

Как я могу получить все дети определенного Simple объекта, где я имею Simple объект, а не все Simple объектов в целом DbSet?

+0

Попробуйте ответить на этот вопрос [сортировка автореферентного Связь] [сортировка S elf-Referencing Relationship]: http://stackoverflow.com/questions/35814586/sorting-self-referencing-relationship/35816143#35816143 –

ответ

1

Я не уверен, что это то, что вы хотите, но это может помочь.

public IQueryable<TEntity> GetItems(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties) 
{ 
    var query = predicate == null 
        ? dbContext.EntitySet<TEntity>() 
        : dbContext.EntitySet<TEntity>().Where(predicate); 

    if (includeProperties != null) 
     query = ApplyIncludesOnQuery(query, includeProperties); 

    return query; 
} 

public IQueryable<TEntity> ApplyIncludesOnQuery(IQueryable<TEntity> query, params Expression<Func<TEntity, object>>[] includeProperties) 
{ 
    //Return Applied Includes query 
    return (includeProperties.Aggregate(query, (currentEntity, navigation) => currentEntity.Include(navigation))); 
} 

Получить все с навигацией

var allItesm = GetItems<Simple>(null, s => s.simpleObjects) 

Конкретным с навигацией

var item = GetItems<Simple>(s => s.Id == someId, s => s.simpleObjects) 

Конкретным без навигации

var item = GetItems<Simple>(s => s.Id == someId) 
+0

Не могли бы вы объяснить, что такое переменная EntitySet()? – user3736648

+0

'EntitySet()' '' DbContext.EntitySet'. –

Смежные вопросы