[英]Refractoring a nested query in Linq to Entity Framework
Supposing I have this query: 假设我有这个查询:
var ps = from p in dc.Products
let text =
(from t in p.Text
orderby t.Language == "ja" descending
select t).FirstOrDefault()
select new { p.Id, text.Name };
Is there any way to refractor the query being assigned to text
? 有什么方法可以使查询分配给text
吗?
My guess is that I need to make it an Expression<Func<Product, string, ProductText>>
, but I don't know how I'd invoke it. 我的猜测是我需要使其成为Expression<Func<Product, string, ProductText>>
,但是我不知道如何调用它。
By the way, if there are more efficient ways to do this, I'd be happy to know. 顺便说一句,如果有更有效的方法可以做到这一点,我很高兴知道。
Thanks, 谢谢,
Rei 丽
Edit: To clarify, the idea is that if Japanese isn't available, I want it to fall back on whatever other language is available. 编辑:澄清一下,想法是,如果日语不可用,我希望它退回到其他可用语言上。
Maybe this is more efficient? 也许这更有效?
let text = p.Text.FirstOrDefault(t => t.Language == "ja") ?? p.Text.FirstOrDefault()
Either way, my main question is about how I might make text
query reusable -- because it's rather unintuitive, and I can picture myself or someone else doing it wrong in the future. 无论哪种方式,我的主要问题都是关于如何使text
查询可重用的-因为这很不直观,并且我可以想象自己或将来其他人做错了。
EDITED BASED ON COMMENT 根据评论进行编辑
var ps = dc.Products.Select(p => new
{
Id = p.Id,
Text = p.Text.OrderBy(t=> t.Language == "ja").First()
})
.Select (x => new
{
Id = x.Id,
Name = x.Name,
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.