实体框架 - n层 - 多对多 - 如何获得列表"其中"

时间:2016-10-19 10:17:19

标签: c# entity-framework many-to-many n-tier-architecture navigation-properties

很多班级

enter image description here

在数据库中,我的表是

enter image description here

enter image description here

enter image description here

我使用EF6和N-Tier并从此post

实现通用数据访问层

我想让Lesson在群组中,我在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;
    }

并在业务层中:

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

调试时,我的代码生成此SQL查询:

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

这不是真的,我想找到Lesson在小组中

  

查找组ID为

的课程

1 个答案:

答案 0 :(得分:1)

您必须检查与该课程相关的组是否包含指定的组ID

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

但为什么不上课与指定的小组相关?

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

    return grp.lesson.ToList(); 
}