我有一个LINQ对象,我希望能够翻转它,以便代替层次结构Orders-> Articles-> Labels,我得到Articles-> Labels-> Orders。
这只是意味着我得到了一篇文章及其所有底层标签。然后,我检查本文属于哪个ORDERS,然后将它们添加为集合。
[176.32.37.27:7777, 54.38.156.202:7777, 51.68.208.5:7777]
我希望
的输出var result = await _unitOfWork.Repository<OrderGroups>().FindByIncludeAsync(
x => GroupIdsClaim.Contains(x.GroupId), b =>
b.Include(v => v.Order)
.ThenInclude(h => h.OrderArticles)
.ThenInclude(t => t.Article)
.ThenInclude(q => q.LabelArticles)
.ThenInclude(p => p.Label));
var orderArticlesLabels = result.Select(x => new
{
x.OrderId,
x.Order.OrderNumber,
Articles = x.Order.OrderArticles.Select(v => new
{
v.ArticleId,
v.Article.Name,
Labels = v.Article.LabelArticles.Select(k => new
{
k.LabelId,
k.Label.Name
})
})
});
但是得到
{
"articleId" = xx,
"name" = "yyy"
"labels" : [],
"orders" : []
}
答案 0 :(得分:2)
如果要实现这一目标:
{
"articleId" = xx,
"name" = "yyy"
"labels" : [],
"orders" : []
}
那你为什么不使用DTO?
public class SomeDTO
{
public int ArticleId { get; set; }
public string Name { get; set; }
public List<LabelArticles> Labels { get; set; }
public List<Orders> Orders { get; set; }
}
var orderArticlesLabels = result.Select(x => new SomeDTO()
{
x.Order.OrderArticles.Select(v => new
{
ArticleId = v.ArticleId,
Name = v.Article.Name,
Labels = v.Article.LabelArticles.Select(k => new
{
LabelId= k.LabelId,
Name= k.Label.Name
}),
Orders = new List<Order>() {new Order() {Id = x.Order.Id,OrderNumber=x.Order.OrderNumber }}
})
});
答案 1 :(得分:2)
您不应该依赖客户端关系修补程序来实现此目的。这施加了严格的限制,例如无法分页或过滤结果。一般规则是开始在要检索的主要实体上导航关系。在这种情况下,这就是文章。
var result = await dbContext.Articles.Where(a =>
a.OrderArticles.Any(oa =>
oa.Order.OrderGroups.Any(og => GroupIdsClaim.Contains(og.GroupId))))
.Include(a => a.LabelArticles)
.ThenInclude(la => la.Label)
.Select(a => new {
ArticleId = a.Id,
a.Name
Labels = a.LabelArticles.Select(la => la.Label)
Orders = a.OrderArticles.Select(oa => oa.Order)
}).Skip().Take().DoAnythingYouWant().ToListAsync();
注意:我不能保证这将转换为有效的SQL或是否会转换。这甚至可能导致n + 1个查询。如果是这样,您可以开始浏览更靠近的GroupId,并通过其他实体执行选择以获取文章。