[英]Many to Many using LinqKit with EF Core with Generic class
我目前正在将 EF 项目转换为 EF Core,但我不知道如何或是否可以:
a) 使用 EF Core 在LinqKit
上使用LinqKit
b) 将 a) 与泛型类一起使用
我目前正在使用以下课程:
protected virtual IQueryable<TEntity> GetQueryable(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = null,
bool isCollection = false,
int? skip = null,
int? take = null)
{
IQueryable<TEntity> query = this.Context.Set<TEntity>();
if (filter != null)
{
query = query.AsExpandable().Where(filter);
}
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split
(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
query = orderBy(query);
}
if (skip.HasValue)
{
query = query.Skip(skip.Value);
}
if (take.HasValue)
{
query = query.Take(take.Value);
}
return query;
}
在 EF 6 中,我将通用类的类型设置为我想要处理的主实体,如果它有多个,我只需将 IncludeProperties 设置为子实体。
例如:
var test = GetQueryable<Company>(null, "Users");
这将返回所有公司并返回与每个相关公司关联的所有用户。
然后,LinqKit 会进来添加额外的过滤器、订单等......
但我无法弄清楚如何在 EF Core 中使用多对多关系使用它。
我看过一个例子,你做类似的事情:
this.Context.Companies.Include("CompanyUsers")
.ThenInclude("Users")
.ToListAsynch()
上面看起来像我需要的,但我需要使用它来通用,我需要使用 LinqKit 或其他方式应用过滤器,但我需要动态设置过滤器、排序、分页等。
有任何想法吗?
谢谢
更新-1:
我的多对多关系类定义如下:
public class CompanyUsers
{
public Guid UserId { get; set; }
public User User { get; set; }
public Guid CompanyId { get; set; }
public Company Company { get; set; }
}
我添加这个的原因是,虽然我的用户表被称为“用户”,但导航属性被称为用户,正如丹尼斯所建议的那样,我应该指定多对多类(公司用户),然后是导航属性(用户)所以而不是:
var test = GetQueryable<Company>(null, "CompanyUsers.Users");
它应该被定义为:
var test = GetQueryable<Company>(null, "CompanyUsers.User");
请注意, s
已被删除以匹配导航属性而不是表格。
最简单的解决方案是使用Include .* 的字符串重载
var test = GetQueryable<Company>(null, "CompanyUsers.User");
*我不建议使用魔法字符串。 您应该考虑编写一个基于模型属性返回 this 的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.