Rei Miyasaka
Rei Miyasaka

Reputation: 7126

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?

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 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.

Upvotes: 0

Views: 479

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39297

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

Upvotes: 1

Related Questions