开发者

Refractoring a nested query in Linq to Entity Framework

开发者 https://www.devze.com 2023-01-23 05:16 出处:网络
Supposing I have this query: var ps = from p in dc.Products let text = (from t in p.Text orderby t.Language == \"ja\" descending

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?

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.

By the way, if there are more efficient ways to do this, I'd be happy to know.

Thanks,

Rei

Edit: To clar开发者_如何学编程ify, 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.


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,
    ...
});
0

精彩评论

暂无评论...
验证码 换一张
取 消