Search code examples
c#entity-frameworkmany-to-manyn-tier-architecturenavigation-properties

entity framework - n-tier - many to many - how to get list "where"


many to many class

enter image description here

in database my table is

enter image description here

enter image description here

enter image description here

I use EF6 and N-Tier and implement a generic data access layer from this post

I want to give Lesson is in the Group ,I Use this Method to Get list in DAL

    public virtual IList<T> GetList(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties)
    {
        List<T> list;
        using (var context = new AzmaEntities())
        {
            IQueryable<T> dbQuery = context.Set<T>();
            foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
                dbQuery = dbQuery.Include<T, object>(navigationProperty);
            list = dbQuery
                .AsNoTracking()
                .Where(where)
                .ToList<T>();
        }
        return list;
    }

and in Business Layer :

    public IList<Lesson> GetLessonWhereGrpId(int grpId)
    {
        Group grp = new Group();
        GroupBLL grpbll = new GroupBLL();
        grp = grpbll.GetGroupById(grpId);

        return _LessonRepository.GetList(
            d => d.Group.Equals(grp)
            );
    }

when debugging , my code Generate this SQL query :

DECLARE @EntityKeyValue1 AS SQL_VARIANT;
SET @EntityKeyValue1 = Null;

SELECT 
    [Extent2].[Id] AS [Id], 
    [Extent2].[Ex_Id] AS [Ex_Id], 
    [Extent2].[Name] AS [Name], 
    [Extent2].[Factor] AS [Factor]
    FROM  [dbo].[LsnToGrp] AS [Extent1]
    INNER JOIN [dbo].[Group] AS [Extent2] ON [Extent1].[Grp_Id] = [Extent2].[Id]
    WHERE [Extent1].[Lsn_Id] = @EntityKeyValue1

This is not ture , I want to find Lesson is in the group

Find Lessons where Group Id is


Solution

  • You have to check if groups related to that lesson contains the specified group id

    public IList<Lesson> GetLessonWhereGrpId(int grpId)
    {
        return _LessonRepository.GetList(
            d => d.Group.Any(x => x.Id == grpId)
            );
    }
    

    But why not getting lessons related to the specified group?

    public IList<Lesson> GetLessonWhereGrpId(int grpId) 
    { 
        GroupBLL grpbll = new GroupBLL(); 
        grp = grpbll.GetGroupById(grpId, g => g.lesson); 
    
        return grp.lesson.ToList(); 
    }