[英]Filter related entities or navigation property where there is a join table in Entity Framework 6
I have three entities Role
, RoleUser
and User
我有三个实体Role
, RoleUser
和User
I want to select each Compulsory Role
and load the related User
's where the RoleUser.RecordID
in the join table is equal to a given value.我想选择每个强制Role
并加载相关的User
,其中连接表中的RoleUser.RecordID
等于给定值。
Using the UOW and GenericReposiity Get(...)
method I would call ...使用 UOW 和 GenericReposiity Get(...)
方法我会调用...
.Get(role => role.Compulsory == true, null, "RoleUser.User")
to select all the compulsory role's and load all User
for the navigation RoleUser.User
. .Get(role => role.Compulsory == true, null, "RoleUser.User")
选择所有强制角色并加载导航RoleUser.User
所有User
。
How can I filter them, is it possible using the implemented Get()
method?如何过滤它们,是否可以使用实现的Get()
方法?
Entities实体
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; }
}
Get得到
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.不,您不能从此 Get 方法过滤RoleUser
。 if you want to filterRoleUser
you want to project them into another list.如果要过滤RoleUser
将它们投影到另一个列表中。You can filter your
Role
based on theRoleUser
table.您可以根据RoleUser
表过滤您的Role
。Include will always bring full data in the table unless you use IQuerable Projection.除非您使用 IQerable Projection,Include 将始终在表中显示完整数据。
var rolesWithAnyUserName = UnitOfWork.Role
.Get(role => role.Compulsory == true && role.RoleUser
.Any(g=>g.RoleUserName=="Name"), null, "RoleUser.User")
This will only filter the Role
based on the RoleUser
filter这只会根据RoleUser
过滤器过滤Role
If you need to filter Include
tables write the query where you can send IQuerable
to the database如果您需要过滤Include
表,请编写查询,您可以将IQuerable
发送到数据库
Try something like this , this will filter both Role
and RoleUser
尝试这样的事情,这将过滤Role
和RoleUser
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.