过滤相关实体或导航 属性,其中在 Entity Framework 中有联接 table 6

Filter related entities or navigation property where there is a join table in Entity Framework 6

我有三个实体 RoleRoleUserUser

我想 select 每个强制 Role 并加载相关的 User,其中连接 table 中的 RoleUser.RecordID 等于给定值。

使用 UOW 和 GenericReposiity Get(...) 方法我会调用...

.Get(role => role.Compulsory == true, null, "RoleUser.User") 至 select 所有强制角色并加载所有 User 用于导航 RoleUser.User.

如何过滤它们,是否可以使用已实现的 Get() 方法?

实体

    public class Role
    {
        public int RoleID { get; set; }

        public bool Compulsory { get; set; }

        public virtual IList<RoleUser> RoleUser { get; set; }       
    }


    public class RoleUser
    {
        public string UserID { get; set; }

        public virtual User User { get; set; }


        public Guid RecordID { get; set; }

        public virtual Record Record { get; set; }


        public int RoleID { get; set; }

        public virtual Role Role { get; set; }
    }


    public class User
    {
        public string userID { get; set; }
    }

获取

    public virtual IList<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

No , you cant filter the RoleUser from this Get method. if you want to filter RoleUser you want to project them into another list.

You can filter your Role based on the RoleUser table.

Include will always bring full data in the table unless you use IQuerable Projection.

var rolesWithAnyUserName = UnitOfWork.Role
                                     .Get(role => role.Compulsory == true && role.RoleUser
                                   .Any(g=>g.RoleUserName=="Name"), null, "RoleUser.User") 

这只会根据 RoleUser 过滤器

过滤 Role

如果您需要过滤 Include 表,请编写查询,您可以将 IQuerable 发送到数据库

尝试这样的操作,这将过滤 RoleRoleUser

var result = DataContext.Role.Where(role => role.Compulsory == true )
                .Include(gl => gl.RoleUser)
                .Select(x => new
                {
                    role = x,
                    roleUsers= x.RoleUser.Where(g => g.Id == 1),
                }).ToList();